jQuery Set Select Index

Dodinas picture Dodinas · Aug 15, 2009 · Viewed 565.3k times · Source

I have an select box:

<select id="selectBox">
  <option value="0">Number 0</option>
  <option value="1">Number 1</option>
  <option value="2">Number 2</option>
  <option value="3">Number 3</option>
  <option value="4">Number 4</option>
  <option value="5">Number 5</option>
  <option value="6">Number 6</option>
  <option value="7">Number 7</option>
</select>

I'd like to set one of the options as "selected" based on it's selected index.

For example, if I am trying to set "Number 3", I'm trying this:

$('#selectBox')[3].attr('selected', 'selected');

But this doesn't work. How can I set an option as selected based on it's index using jQuery?

Thanks!

Answer

Marc picture Marc · Aug 15, 2009

NOTE: answer is dependent upon jQuery 1.6.1+

$('#selectBox :nth-child(4)').prop('selected', true); // To select via index
$('#selectBox option:eq(3)').prop('selected', true);  // To select via value

Thanks for the comment, .get won't work since it returns a DOM element, not a jQuery one. Keep in mind the .eq function can be used outside of the selector as well if you prefer.

$('#selectBox option').eq(3).prop('selected', true);

You can also be more terse/readable if you want to use the value, instead of relying on selecting a specific index:

$("#selectBox").val("3");

Note: .val(3) works as well for this example, but non-numeric values must be strings, so I chose a string for consistency.
(e.g. <option value="hello">Number3</option> requires you to use .val("hello"))