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?
If you don’t mind modifying your HTML a little to include the
valueattribute of the options, you can significantly reduce the code necessary to do this:to
This will be helpful when you want to do something like:
With that, the follow jQuery will make the change:
If you decide not to include the use of the
valueattribute, you will be required to cycle through each option, and manually check its value: