Setting the selected attribute on a select list using jQuery

Rupert picture Rupert · Aug 21, 2009 · Viewed 274.8k times · Source

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?

Answer

Sampson picture Sampson · Aug 21, 2009

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");
});