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!
Select the item based on the value in the select list (especially if the option values have a space or weird character in it) by simply doing this:
Also, if you have a dropdown (as opposed to a multi-select) you may want to do a
break;
so you don't get the first-value-found to be overwritten.when you want to select with top ways for set selection , you can use
$('#select option').removeAttr('selected');
for remove previous selects .select 3rd option
Example on jsfiddle
I faced same problem. First you need go through the events (i.e which event is happening first).
For example:
The First event is generating select box with options.
The Second event is selecting default option using any function such as val() etc.
You should ensure that the Second event should happen after the First event.
To achieve this take two functions lets say generateSelectbox() (for genrating select box) and selectDefaultOption()
You need to ensure that selectDefaultOption() should be called only after the execution of generateSelectbox()
To clarify Marc's and John Kugelman's answers, you could use:
get()
will not work if used in the way specified because it gets the DOM object, not a jQuery object, so the following solution will not work:eq()
gets filters the jQuery set to that of the element with the specified index. It's clearer than$($('#selectBox option').get(3))
. It's not all that efficient.$($('#selectBox option')[3])
is more efficient (see test case).You don't actually need the jQuery object though. This will do the trick:
http://api.jquery.com/get/
http://api.jquery.com/eq/
One other vitally important point:
The attribute "selected" is not how you specify a selected radio button (in Firefox and Chrome at least). Use the "checked" attribute:
The same goes for check-boxes.
you can set selectoption variable value dynamically as well as option will be selected.You can try following code
code:
HTML CODE: