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
$(this)
only works inside jQuery functions; it references nothing inside fun()
. Instead, try this:
$('input#desc').click(function() {
alert($(this).attr('id'));
});
With this HTML:
<input type="text" id="desc" name="txtTitle">
It's not particularly good practice to have onClick=""
attributes in your HTML, hence the $.click()
function given above. You should always put your JavaScript in a separate file (especially when using jQuery).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With