How do you select a particular option in a SELECT

2018-12-31 15:12发布

If you know the Index, Value or Text. also if you don't have an ID for a direct reference.

This, this and this are all helpful answers.

Example markup

<div class="selDiv">
  <select class="opts">
    <option selected value="DEFAULT">Default</option>
    <option value="SEL1">Selection 1</option>
    <option value="SEL2">Selection 2</option>
  </select>
</div>

标签: jquery
19条回答
与风俱净
2楼-- · 2018-12-31 16:04

For setting select value with triggering selected:

$('select.opts').val('SEL1').change();

For setting option from a scope:

$('.selDiv option[value="SEL1"]')
    .attr('selected', 'selected')
    .change();

This code use selector to find out the select object with condition, then change the selected attribute by attr().


Futher, I recommend to add change() event after setting attribute to selected, by doing this the code will close to changing select by user.

查看更多
登录 后发表回答