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/
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. $("div. id_100 > select > option[value=" + value + "]").
In order to change the selected option by the value attribute, all we have to do is change the value property of the <select> element.
The select tag in HTML is used to create a dropdown list of options that can be selected. The option tag contains the value that would be used when selected. The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute.
Definition and UsageThe selected attribute is a boolean attribute. When present, it specifies that an option should be pre-selected when the page loads. The pre-selected option will be displayed first in the drop-down list. Tip: The selected attribute can also be set after the page loads, with a JavaScript.
There's an easier way that doesn't require you to go into the options tag:
$("div.id_100 select").val("val2");
Check out this jQuery method.
Note: The above code does not trigger the change event. You need to call it like this for full compatibility:
$("div.id_100 select").val("val2").change();
To select an option with value 'val2':
$('.id_100 option[value=val2]').attr('selected','selected');
Use the change()
event after selecting the value. From the documentation:
If the field loses focus without the contents having changed, the event is not triggered. To trigger the event manually, apply
.change()
without arguments:
$("#select_id").val("val2").change();
More information is at .change().
Deselect all first and filter the selectable options:
$('.id_100 option')
.removeAttr('selected')
.filter('[value=val1]')
.attr('selected', true)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With