Lewis Day Lewis Day - 1 month ago 8
Javascript Question

on-click input a id into input field

What I'm trying to achieve is instead of the text inside the

<a href="#">Text Inside</a>
being inputted into the input field I would like the
a id
to be inputted. so for example if the first link is clicked with the
a id
of
1
. 1 is then inputted into the text field.

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


<input id="text_tag_input" type="text" name="tags" />

<div class="tags_select">
<a id="1" href="#">text1</a>
<a id="2" href="#">text2</a>
<a id="3" href="#">text3</a>
</div>

Answer

Your posted code will work almost as written for this functionality, you simply have to retrieve the id instead of the text:

$(function() {
    $('.tags_select a').click(function() {

        // this.id retrieves the id attribute/property value
        // of the 'this' element (here the clicked <a> element:
        var value = this.id;
        var input = $('#text_tag_input');
        input.val(input.val() + value + ', ');
        return false;
    });
});

Although the above works, I'd suggest a minor tidy-up:

$(function() {
    $('.tags_select a').click(function() {
        var clicked = this;
        $('#text_tag_input').val(function(i,v){
          return v += clicked.id + ', ';
        });
        return false;
    });
});

You could also do the same thing, relatively easily, in plain JavaScript:

function addToElementText() {
  var clicked = this;

    document.querySelector(clicked.dataset.selector).value += clicked[clicked.dataset.property] + ', ';

}

var links = document.querySelectorAll('.tags_select a');

Array.prototype.slice.call(links).forEach(function(link) {
  link.addEventListener('click', addToElementText);
});

The above JavaScript requires that the <a> elements have an additional attribute to convey the required selector for the element to which the the chosen property should be added, and another to select the relevant property-value to be added:

<a href="#" id="1" data-selector="#text_tag_input" data-property="id">link text</a>
Comments