tutor777 tutor777 - 7 months ago 27
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()">


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

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

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

but it alerts


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.