tutor777 tutor777 - 3 months ago 7
jQuery Question

Alert ID of current element

I'm using following code to alert id of current element.

<input type="text" id="desc" name="txtTitle" onclick="fun()">


jquery:

function fun () {
var currentId = $(this).attr('id');
alert(currentId);
}


Why does it alert "undefined"?
I have tried with:

var currentId =$('element').attr('id');
// and
alert($(this).id);
// and
alert(this.id);


but it alerts
undefined

Answer

Try changing it to:

<input type="text" id="desc" name="txtTitle" onclick="fun.call(this)">

Better, bind your event handler with jQuery, since you're using it anyway:

$(function() { $('#desc').click(fun); });

The reason your code doesn't work is that you're calling fun() from inside the event handler function constructed by the browser for your "onclick" attribute. By just calling the function like that, you provide no "receiver" object — nothing for this to be, that is. If you call it with .call() however you can explicitly do that.