jquery $(this).id return Undefined
I have two asp radio buttons on a page that are placed in a updatepanel
. I wrote a click event for them with jQuery like this:
$(document).ready(function () {
$(".inputs").click(function () {
alert($(this).id);
});
});
But it returns Undefined. What is the problem?
EDIT:
alert(" or " + $(this).attr("id"));
alert(this.id);
These two lines return null
!
Solution 1:
$(this)
and this
aren't the same. The first represents a jQuery object wrapped around your element. The second is just your element. The id
property exists on the element, but not the jQuery object. As such, you have a few options:
-
Access the property on the element directly:
this.id
-
Access it from the jQuery object:
$(this).attr("id")
-
Pull the object out of jQuery:
$(this).get(0).id; // Or $(this)[0].id
-
Get the
id
from theevent
object:When events are raised, for instance a click event, they carry important information and references around with them. In your code above, you have a click event. This event object has a reference to two items:
currentTarget
andtarget
.Using
target
, you can get theid
of the element that raised the event.currentTarget
would simply tell you which element the event is currently bubbling through. These are not always the same.$("#button").on("click", function(e){ console.log( e.target.id ) });
Of all of these, the best option is to just access it directly from this
itself, unless you're engaged in a series of nested events, then it might be best to use the event
object of each nested event (give them all unique names) to reference elements in higher or lower scopes.
Solution 2:
Another option (just so you've seen it):
$(function () {
$(".inputs").click(function (e) {
alert(e.target.id);
});
});
Solution 3:
Hiya demo http://jsfiddle.net/LYTbc/
This is a reference to the DOM element, so you can wrap it directly.
attr
API: http://api.jquery.com/attr/
The .attr() method gets the attribute value for only the first element in the matched set.
Have a nice one, cheers!
code
$(document).ready(function () {
$(".inputs").click(function () {
alert(this.id);
alert(" or " + $(this).attr("id"));
});
});
Solution 4:
$(this)
is a jQuery object that is wrapping the DOM element this
and jQuery objects don't have id
properties. You probably want just this.id
to get the id
attribute of the clicked element.