Reputation: 141
I'm trying to return the ID of an anchor tag in javascript in Django, however for some reason it always returns "undefined".
HTML:
<div class="list-group">
<a href="#" class="list-group-item active">Select Drug</a>
{% for drug in drugs %}
<a id="TESTING" href="javascript:AddToList()" class="list-group-item drugName">
{{ drug }}</a>
{% endfor %}
</div>
Javascript:
function AddToList() {
alert($(this).attr('id'));
}
Upvotes: 1
Views: 642
Reputation: 133403
Simplest solution is top pass the this
, reference to the element which invoke the event to the event handler AddToList
. Then event handler just fetch the id
property from element.
HTML
<a id="TESTING" href="javascript:AddToList(this)" class="list-group-item drugName">
Script
function AddToList(elem) {
alert(elem.id);
}
Since you are using jQuery, I would recommend you to bind event handler using it
HTML
<a id="TESTING" class="list-group-item drugName">
Script
function AddToList() {
alert(this.id);
}
//DOM Ready handler
$(function(){
//Use class selector to bind event handler
$('.drugName').on('click', AddToList)
//Or, Use ID selector to bind event handler
$('#TESTING').on('click', AddToList)
});
Upvotes: 1