Sometimes we need to find the selected option in a select component.
HMTL
<select name=”options” id=”optionsById”>
<option value=”1″>Red</option>
<option value=”2″ selected=”1″>Green</option>
<option value=”3″>Blue</option>
</select>
Javascript
//remove selected one
$(‘option:selected’, ‘select[name=”options”]’).removeAttr(‘selected’);
//Using the value by name
$(‘select[name=”options”]’).find(‘option[value=”3″]’).attr(“selected”,true);
//or
$(‘select[name=”options”]’).find(‘option[value=”3″]’).prop(“selected”,true);
//or
$(‘select[name=”options”]’).val(‘3’);
//Using the value by id
$(‘#optionsById option:eq(“1”)’).prop(“selected”,true);
//Using the text
$(‘select[name=”options”]’).find(‘option:contains(“Blue”)’).attr(“selected”,true);