Friday, April 8, 2011

Why can't I access any properties on my jQuery-returned object?

Hi!

I have the following javascript:

$(document).ready(function() {
    $('#<%= DropDownList1.ClientID %>').change(function() {
        $('#<%= TextBox1.ClientID %>').disabled = $('#<%= DropDownList1.ClientID %>').selectedIndex != 1;
    });
});

When I change the index of the dropdown, nothing happens. I have tried to replace the code with:

$(document).ready(function() {
    $('#<%= DropDownList1.ClientID %>').change(function() {
        alert($('#<%= DropDownList1.ClientID %>').id);                    
    });
});

This generates an alert that says 'undefined'. If I remove the .id-part I get an alert that says [object Object] so I guess it has got something. What am I doing wrong?

From stackoverflow
  • One key thing to realize in jQuery is that what is returned by the $(selector) is a jQuery object, not the DOM object. If you want to get the value for the select box from the jQuery object, you can use the val() function as in:

    $("#element").val();
    

    If you want to access the dom element from the jQuery object, that is easy, too. You can use the following:

    $("#element")[0]; // equivalent to $("#element").get(0)
    

    That should help you solve your problem.

  • $(document).ready(function()
    {
        $('#<%= DropDownList1.ClientID %>').change(function()
        {
            // replace 'your value' with the value of dropdown selectedIndex 1
            if ($('#<%= DropDownList1.ClientID %>').val() == 'your value')
                $('#<%= TextBox1.ClientID %>').removeAttr('disabled');
            else
                $('#<%= TextBox1.ClientID %>').attr('disabled', 'disabled');
        });
    });
    

0 comments:

Post a Comment