Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alert ID of current element

Tags:

jquery

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

like image 348
dynid Avatar asked Jan 29 '12 14:01

dynid


2 Answers

$(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).

like image 167
Bojangles Avatar answered Sep 30 '22 02:09

Bojangles


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.

like image 33
Pointy Avatar answered Sep 30 '22 03:09

Pointy