Smartik Smartik - 5 months ago 27
jQuery Question

Javascript to Jquery, add text in 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 a user click the link text automaticaly is added in input.

This is the 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 the demo: http://jsfiddle.net/Smartik/j8qGT/

Answer
<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's a live demo.

Comments