Set select option 'selected', by value

2018-12-31 21:04发布

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/

21条回答
余欢
2楼-- · 2018-12-31 21:50

.attr() sometimes doesn't work in older jQuery versions, but you can use .prop():

$('select#ddlCountry option').each(function () {
    if ($(this).text().toLowerCase() == co.toLowerCase()) {
        $(this).prop('selected','selected');
        return;
    }
});
查看更多
看淡一切
3楼-- · 2018-12-31 21:53

It's better to use change() after setting select value.

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

By doing this, the code will close to changing select by user, the explanation is included in JS Fiddle:

JS Fiddle

查看更多
ら面具成の殇う
4楼-- · 2018-12-31 21:53

This works for sure for Select Control:

$('select#ddlCountry option').each(function () {
if ($(this).text().toLowerCase() == co.toLowerCase()) {
    this.selected = true;
    return;
} });
查看更多
泪湿衣
5楼-- · 2018-12-31 21:54

You can select on any attribute and its value by using the attribute selector [attributename=optionalvalue], so in your case you can select the option and set the selected attribute.

$("div.id_100 > select > option[value=" + value + "]").prop("selected",true);

Where value is the value you wish to select by.

If you need to removed any prior selected values, as would be the case if this is used multiple times you'd need to change it slightly so as to first remove the selected attribute

$("div.id_100 option:selected").prop("selected",false);
$("div.id_100 option[value=" + value + "]")
        .prop("selected",true);
查看更多
初与友歌
6楼-- · 2018-12-31 21:54

The easiest way to do that is:

HTML

<select name="dept">
   <option value="">Which department does this doctor belong to?</option>
   <option value="1">Orthopaedics</option>
   <option value="2">Pathology</option>
   <option value="3">ENT</option>
</select>

jQuery

$('select[name="dept"]').val('3');

Output: This will activate ENT.

查看更多
孤独总比滥情好
7楼-- · 2018-12-31 21:55

To select an option with value 'val2':

$('.id_100 option[value=val2]').attr('selected','selected');
查看更多
登录 后发表回答