Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the selected attribute on a select list using jQuery

I have the following HTML:

<select id="dropdown">     <option>A</option>     <option>B</option>     <option>C</option> </select> 

I have the string "B" so I want to set the selected attribute on it so it will be:

<select id="dropdown">     <option>A</option>     <option selected="selected">B</option>     <option>C</option> </select> 

How would I do this in jQuery?

like image 782
Rupert Avatar asked Aug 21 '09 10:08

Rupert


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 selected box using jQuery?

You can select on any attribute and its value by using the attribute selector [attributename=optionalvalue] , so in your case you can select the option and set the selected attribute. $("div. id_100 > select > option[value=" + value + "]"). prop("selected",true);

How do I change selected option in select tag?

In order to change the selected option by the value attribute, all we have to do is change the value property of the <select> element. The select box will then update itself to reflect the state of this property. This is the easiest and most straightforward way of updating a select box state.

How do you display a selected value in a drop down list?

Method 1: Using the value property: The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.


1 Answers

If you don't mind modifying your HTML a little to include the value attribute of the options, you can significantly reduce the code necessary to do this:

<option>B</option> 

to

<option value="B">B</option> 

This will be helpful when you want to do something like:

<option value="IL">Illinois</option> 

With that, the follow jQuery will make the change:

$("select option[value='B']").attr("selected","selected"); 

If you decide not to include the use of the value attribute, you will be required to cycle through each option, and manually check its value:

$("select option").each(function(){   if ($(this).text() == "B")     $(this).attr("selected","selected"); }); 
like image 117
Sampson Avatar answered Sep 18 '22 04:09

Sampson