Advertisement
Advertisement


Set select option 'selected', by value


Question

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/

2016/07/02
1
981
7/2/2016 9:37:09 PM

Accepted Answer

There's an easier way that doesn't require you to go into the options tag:

$("div.id_100 select").val("val2");

Check out the this jQuery method.

2017/09/21
1573
9/21/2017 3:51:46 PM

To select an option with value 'val2':

$('.id_100 option[value=val2]').attr('selected','selected');
2016/07/02

Use the change() event after selecting the value. From the docs:

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().

2017/01/27

Deselect all first and filter the selectable options:

$('.id_100 option')
     .removeAttr('selected')
     .filter('[value=val1]')
         .attr('selected', true)
2016/06/25

<select name="contribution_status_id" id="contribution_status_id" class="form-select">
    <option value="1">Completed</option>
    <option value="2">Pending</option>
    <option value="3">Cancelled</option>
    <option value="4">Failed</option>
    <option value="5">In Progress</option>
    <option value="6">Overdue</option>
    <option value="7">Refunded</option>

Setting to Pending Status by value

   $('#contribution_status_id').val("2");
2013/12/05

For me the following did the job

$("div.id_100").val("val2").change();
2016/07/27