Tony
Tony

Reputation: 12695

jQuery a problem with retrieving an element's id

in the code below, I need to get the ID of the element that has raised the event

$(document).ready(function () 
{
    $(".selectors").live('change', function () 
    {
        $.post("GetCategoriesByParentId/", { ID: $(this).val() }, function (data) 
        {
            var idd = $(this).attr('id'); //here
        });
    });
});

but the idd is always 'Undefined'. Why ?

Upvotes: 0

Views: 88

Answers (2)

Bryan A
Bryan A

Reputation: 3634

The $(this) inside your .post function is not actually the current element in the set you're iterating through in the parent loop. Fix:

$(".selectors").live('change', function () 
{
    $thisElement = $(this);

    $.post("GetCategoriesByParentId/", { ID: $(this).val() }, function (data) 
    {
        var idd = $thisElement.attr('id'); //here
    });
});

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237865

In the context of the $.post callback, the value of this will be set to something different to that of the live call. You'll need to cache the value of this:

$(document).ready(function () 
{
    $(".selectors").live('change', function () 
    {
        var idd = this.id;

        $.post("GetCategoriesByParentId/", { ID: $(this).val() }, function (data) 
        {
            // idd is now the id of the changed element
        });
    });
});

Upvotes: 3

Related Questions