Javascript for jQuery, add text to input onclick
How can I change this javascript code to jQuery.
<script type="text/javascript">
function addTextTag(text){
document.getElementById('text_tag_input').value += text;
}
</script>
When the user clicks the link text, the text is automatically added.
This is HTML:
<input id="text_tag_input" type="text" name="tags" />
<div class="tags_select">
<a href="#" onClick="addTextTag('text1, '); return false">text1</a>
<a href="#" onClick="addTextTag('text2, '); return false">text2</a>
<a href="#" onClick="addTextTag('text3, '); return false">text3</a>
</div>
Here is a demo: http://jsfiddle.net/Smartik/j8qGT/
<script type="text/javascript">
$(function() {
$('.tags_select a').click(function() {
var value = $(this).text();
var input = $('#text_tag_input');
input.val(input.val() + value + ', ');
return false;
});
});
</script>
and your markup:
<input id="text_tag_input" type="text" name="tags" />
<div class="tags_select">
<a href="#">text1</a>
<a href="#">text2</a>
<a href="#">text3</a>
</div>
and here is a live demonstration .
Without built-in javascript, fully jQuery: http://jsfiddle.net/j8qGT/3/
JavaScript:
$('a').click(function(){
$('#text_tag_input').val($('#text_tag_input').val()+$(this).html()+', ');
});
HTML:
<input id="text_tag_input" type="text" name="tags" />
<div class="tags_select">
<a href="#">text1</a>
<a href="#">text2</a>
<a href="#">text3</a>
</div>
:
, , :
var $tagsInput = $('#text_tag_input');. , ID jQuery,document.getElementByIdclick .click() "tags_select": `$ ('. tags_select a). click (...);` `
To add a value, instead of struggling with jquery methods to get and set the value of an input, get your own DOM element with
[0]on$tagsInputand use+=property notationvalue.
Here is the code:
// select already you input element for re-use
var $tagsInput = $('#text_tag_input');
// bind a click event to links within ".tags-select" element
$('.tags_select a').click(function() {
// append link text to the input field value
$tagsInput[0].value += $(this).text();
return false;
});
Further reading: