javascript tutorial - [Solved-5 Solutions] Change the selected value of a drop-down list with jQuery - javascript - java script - javascript array



Problem:

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 too.
click below button to copy the code. By JavaScript tutorial team

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.
click below button to copy the code. By JavaScript tutorial team

How can I do it with jQuery? Update So as it turns out, I had it right the first time with:

$("._statusDDL").val(2);
click below button to copy the code. By JavaScript tutorial team

When I put an alert just above 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.

Solution 1:

This behavior is in jQuery versions 1.2 and above. You most likely want this:

$("._statusDDL").val('2');
click below button to copy the code. By JavaScript tutorial team

Solution 2:

With hidden field you need to use like this:

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

click below button to copy the code. By JavaScript tutorial team

Solution 3:

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");
click below button to copy the code. By JavaScript tutorial team

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

Solution 4:

Just try with

$("._statusDDL").val("2");
click below button to copy the code. By JavaScript tutorial team

and not with

$("._statusDDL").val(2);
click below button to copy the code. By JavaScript tutorial team

Solution 5:

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

$.extend({
    clientID: function(id) {
        return $("[id$='" + id + "']");
    }
});
click below button to copy the code. By JavaScript tutorial team

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

$.clientID("_statusDDL")
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Change the selected value of a drop-down list with jQuery