Sunday, June 3, 2012

Change the selected value of a drop-down list with jQuery


I have a drop-down list with known values. What I'm trying to do is set the drop down list to a particular value that I know exists using jQuery. Using regular JavaScript, I would do something like:




ddl = document.getElementById("ID of element goes here");
ddl.value = 2; // 2 being the value I want to set it to.



However, I need to do this with jQuery, because I'm using a CSS class for my selector (stupid ASP.NET client ids...).



Here are a few things I've tried:




$("._statusDDL").val(2); // Doesn't find 2 as a value.
$("._statusDDL").children("option").val(2) // Also failed.



How can I do it with jQuery?



Update



So as it turns out, I had it right the first time with:




$("._statusDDL").val(2);



When I put an alert just above it it works fine, but when I remove the alert and let it run at full speed, I get the error




Could not set the selected property. Invalid Index




I'm not sure if it's a bug with jQuery or Internet Explorer 6 (I'm guessing Internet Explorer 6), but it's terribly annoying.


Source: Tips4all

10 comments:

  1. jQuery's documentation states:


    [jQuery.val] checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.


    This behavior is in jQuery versions 1.2 and above.

    You most likely want this:

    $("._statusDDL").val('2');

    ReplyDelete
  2. Just an FYI, you don't need to use CSS classes to accomplish this.

    You can write the following line of code to get the correct control name on the client:

    $("#<%= statusDDL.ClientID %>").val("2");


    ASP.NET will render the control ID correctly inside the jQuery.

    ReplyDelete
  3. Just try with

    $("._statusDDL").val("2");

    and not with

    $("._statusDDL").val(2);

    ReplyDelete
  4. So I changed it so that now it
    executes after a 300 miliseconds using
    setTimeout. Seems to be working now.


    I have run into this many times when loading data from an Ajax call. I too use .NET, and it takes time to get adjusted to the clientId when using the jQuery selector. To correct the problem that you're having and to avoid having to add a setTimeout property, you can simply put "async: false" in the Ajax call, and it will give the DOM enough time to have the objects back that you are adding to the select. A small sample below:

    $.ajax({
    type: "POST",
    url: document.URL + '/PageList',
    data: "{}",
    async: false,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
    var pages = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

    $('#locPage' + locId).find('option').remove();

    $.each(pages, function () {
    $('#locPage' + locId).append(
    $('<option></option>').val(this.PageId).html(this.Name)
    );
    });
    }
    });

    ReplyDelete
  5. Just a note - I've been using wildcard selectors in jQuery to grab items that are obfuscated by ASP.NET CLient IDs - this might help you too:

    <asp:DropDownList id="MyDropDown" runat="server" />

    $("[id* = 'MyDropDown']").append("<option value='-1'>&nbsp;</option>"); //etc


    Note the id* wildcard- this will find your element even if the name is "ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$MyDropDown"

    ReplyDelete
  6. How are you loading the values into the drop down list or determining which value to select? If you are doing this using Ajax, then the reason you need the delay before the selection occurs could be because the values were not loaded in at the time that the line in question executed. This would also explain why it worked when you put an alert statement on the line before setting the status since the alert action would give enough of a delay for the data to load.

    If you are using one of jQuery's Ajax methods, you can specify a callback function and then put $("._statusDDL").val(2); into your callback function.

    This would be a more reliable way of handling the issue since you could be sure that the method executed when the data was ready, even if it took longer than 300 ms.

    ReplyDelete
  7. <asp:DropDownList id="MyDropDown" runat="server" />

    Use $("select[name$='MyDropDown']").val().

    ReplyDelete
  8. I use an extend function to get client ids, like so:

    $.extend({
    clientID: function(id) {
    return $("[id$='" + id + "']");
    }
    });


    Then you can call ASP.NET controls in jQuery like this:

    $.clientID("_statusDDL")

    ReplyDelete
  9. Another option is to set the control param ClientID="Static" in .net and then you can access the object in JQuery by the ID you set.

    ReplyDelete
  10. Afert looking some solutions this worked for me

    I have one dropdown list with some values and i want to select the same value to other dropdown list..
    so firt I put in a variable the selectIndex of my first droprown.
    var indiceDatos = $('#myidddl')[0].selectedIndex;

    after, i select that index on my second dropdownlist.
    $('#myidddl2')[0].selectedIndex = indiceDatos;

    ReplyDelete