Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 693
Andrei Surdu Avatar asked Feb 26 '12 10:02

Andrei Surdu


3 Answers

<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.

like image 70
Darin Dimitrov Avatar answered Oct 30 '22 14:10

Darin Dimitrov


Without inline javascript, completely 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>​
like image 44
Alex Avatar answered Oct 30 '22 14:10

Alex


Some notes on the steps:

  • select already the input where to set the value so you avoid the need to re-query for it all the time: var $tagsInput = $('#text_tag_input');. The hash tag selector if the ID selector in jQuery, replaces document.getElementById

  • bind a click event with .click() for links within element with class "tags_select": `$('.tags_select a').click(...);``

  • To append the value, instead of struggling with jquery methods to get and set the value of the input, get the native DOM element with [0] on $tagsInput and use the += notation of the property value.

Here's 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;
});

DEMO

Further reading:

  • jQuery selectors
  • Bind a click event with .click()
like image 2
Didier Ghys Avatar answered Oct 30 '22 15:10

Didier Ghys