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/
Use the
change()
event after selecting the value. From the docs:More information is at .change().
For me the following did the job
There's no reason to overthink this, all you are doing is accessing and setting a property. That's it.
Okay, so some basic dom: If you were doing this in straight JavaScript, it you would this:
But you're not doing it with straight JavaScript, you're doing it with jQuery. And in jQuery, you want to use the .prop() function to set a property, so you would do it like this:
Anyway, just make sure your id is unique. Otherwise, you'll be banging your head on the wall wondering why this didn't work.
case sensative
. You can change your select box dynamically as follows,$("div#YOUR_ID").val(VALUE_CHANGED).change(); //value must present in options you selected otherwise it will not work
Try this. Simple yet effective javaScript + jQuery the lethal combo.
SelectComponent :
Selection :
Now your option 4 will be selected. You can do this, to select the values on start by default.
or create a simple function put the line in it and call the function on anyEvent to select the option
A mixture of jQuery + javaScript does the magic....
Deselect all first and filter the selectable options: