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
Try changing it to:
Better, bind your event handler with jQuery, since you’re using it anyway:
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 forthisto be, that is. If you call it with.call()however you can explicitly do that.