How to select option in dropdown menu using jQuery

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);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s