Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 too. 

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

like image 984
phairoh Avatar asked Jan 31 '09 19:01

phairoh


People also ask

How can I change the selected value of a Dropdownlist using jQuery?

Using the jQuery change() method; you can set the selected value of dropdown in jquery by using id, name, class, and tag with selected html elements; see the following example for that: Example 1 :- Set selected value of dropdown in jquery by id.

How do I select a Dropdownlist using jQuery?

We can select text or we can also find the position of a text in a drop down list using option:selected attribute or by using val() method in jQuery. By using val() method : The val() method is an inbuilt method in jQuery which is used to return or set the value of attributes for the selected elements.

How can set the selected value of dropdown in HTML?

The select tag in HTML is used to create a dropdown list of options that can be selected. The option tag contains the value that would be used when selected. The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute.


2 Answers

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'); 
like image 141
strager Avatar answered Oct 04 '22 16:10

strager


With hidden field you need to use like this:

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

or

$("._statusDDL").val(2).change(); 
like image 38
Aivar Luist Avatar answered Oct 04 '22 15:10

Aivar Luist