我有一个选择字段,其中有一些选项。现在我需要用jQuery选择其中一个选项。但是,当我只知道必须选择的选项的值时,我该怎么做呢?

我有以下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>

我需要选择值为val2的选项。如何做到这一点呢?

这是一个演示页面: http://jsfiddle.net/9Stxb/


当前回答

最好的方法是这样的:

$(`#YourSelect option[value='${YourValue}']`).prop('selected', true);

其他回答

最好的方法是这样的:

$(`#YourSelect option[value='${YourValue}']`).prop('selected', true);

选择值为'val2'的选项:

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

这肯定适用于选择控件:

$('select#ddlCountry option').each(function () {
if ($(this).text().toLowerCase() == co.toLowerCase()) {
    this.selected = true;
    return;
} });

感谢傻瓜的回答:

在我的例子中,我需要使用的组合

$('.id_100 option')
     .removeAttr('selected')
     .filter('[value=val1]')
         .prop('selected', true);

$('.id_100').val("val1").change(); // I need to set the same value here for my next form submit.

为下一次表单提交设置正确的值。当使用这个时,即使我有另一个on change事件有界,它也不会给出一个无限循环。

最好在设置select value之后使用change()。

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

通过这样做,代码将关闭更改用户的选择,解释包括在JS提琴:

JS小提琴