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?
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.
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);
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.
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.
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"); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With