select

Change selected option by value on select list with jQuery

Posted by on Aug 10, 2010 in Frontend | 3 comments

You have a select element, and you need to “select” one of its options based on one of its values. What you do is use the “selected-selector” of jQuery to do it in a single line.

Lets say I have the following select element and I need to dynamically select the option with a value of 3, which would be the “Peach”.

<select name="myselect" id="myselect">
	<option value="1">Apple</option>
	<option value="2">Pear</option>
	<option value="3">Peach</option>
	<option value="4">Orange</option>
</select>

 

$("#myselect option[value=3]").attr('selected', 'selected');

// Or just...
$("#myselect").val(3);

If you want to get a little bit more technical, make sure you read the official jQuery documentation regarding this subject.