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!
Try this instead:
also, see if this helps you:
http://elegantcode.com/2009/07/01/jquery-playing-with-select-dropdownlistcombobox/
The pure javascript selectedIndex attribute is the right way to go because,it's pure javascript and works cross-browser:
Here is a jsfiddle demo with two dropdowns using one to set the other:
You can also call this before changing the selectedIndex if what you want is the "selected" attribute on the option tag (here is the fiddle):
I need a solution that has no hard coded values in the js file; using
selectedIndex
. Most of the given solutions failed one browser. This appears to work in FF10 and IE8 (can someone else test in other versions)If you just want to select an item based of a particular property of an item then jQuery option of type[prop=val] will get that item. Now I don't care about the index I just wanted the item by its value.
What's important to understand is that
val()
for aselect
element returns the value of the selected option, but not the number of element as doesselectedIndex
in javascript.To select the option with
value="7"
you can simply use:To deselect the option use an empty array:
And of course you can select multiple options*:
*However to select multiple options, your
<select>
element must have aMULTIPLE
attribute, otherwise it won't work.