I have a select
field with some options in it. Now I need to select one of those options
with jQuery. But how can I do that when I only know the value
of the option
that must be selected?
I have the following HTML:
<div class="id_100">
<select>
<option value="val1">Val 1</option>
<option value="val2">Val 2</option>
<option value="val3">Val 3</option>
</select>
</div>
I need to select the option with value val2
. How can this be done?
Here's a demo page: http://jsfiddle.net/9Stxb/
.attr() sometimes doesn't work in older jQuery versions, but you can use .prop():
It's better to use
change()
after setting select value.By doing this, the code will close to changing select by user, the explanation is included in JS Fiddle:
JS Fiddle
This works for sure for Select Control:
You can select on any attribute and its value by using the attribute selector
[attributename=optionalvalue]
, so in your case you can select the option and set the selected attribute.Where
value
is the value you wish to select by.If you need to removed any prior selected values, as would be the case if this is used multiple times you'd need to change it slightly so as to first remove the selected attribute
The easiest way to do that is:
HTML
jQuery
To select an option with value 'val2':