Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery $(this).id return Undefined

Tags:

jquery

asp.net

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!

like image 426
Mahdi_Nine Avatar asked May 14 '12 06:05

Mahdi_Nine


4 Answers

$(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:

  1. Access the property on the element directly:

    this.id

  2. Access it from the jQuery object:

    $(this).attr("id")

  3. Pull the object out of jQuery:

    $(this).get(0).id; // Or $(this)[0].id

  4. Get the id from the event 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 and target.

    Using target, you can get the id 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.

like image 146
Sampson Avatar answered Oct 15 '22 02:10

Sampson


Another option (just so you've seen it):

$(function () {
    $(".inputs").click(function (e) {
         alert(e.target.id);
    });
});
like image 45
Tieson T. Avatar answered Oct 15 '22 02:10

Tieson T.


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"));
    });
});​
like image 9
Tats_innit Avatar answered Oct 15 '22 03:10

Tats_innit


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

like image 4
mu is too short Avatar answered Oct 15 '22 02:10

mu is too short