我有一个选择字段,其中有一些选项。现在我需要用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/


当前回答

我需要选择一个选项,但两个选项可能具有相同的值。 这纯粹是为了视觉(前端)的差异。 你可以选择一个选项(即使两个值相同),如下所示:

let options = $('#id_100 option')
options.prop('selected', false)   // Deselect all currently selected ones
let option = $(options[0])        // Select option from the list
option.prop('selected', true)
option.parent().change()          // Find the <select> element and call the change() event.

这将取消当前选中的所有<option>元素。选择第一个元素(使用选项[0]),并使用change事件更新<select>元素。

其他回答

最好的方法是这样的:

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

选择值为'val2'的选项:

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

我认为最简单的方法是选择设置val(),但你可以检查以下。查看如何处理选择和选项标签在jQuery?有关选项的详细信息。

$('div.id_100  option[value="val2"]').prop("selected", true);

$('id_100').val('val2');

没有优化,但下面的逻辑在某些情况下也很有用。

$('.id_100 option').each(function() {
    if($(this).val() == 'val2') {
        $(this).prop("selected", true);
    }
});

选择值后使用change()事件。从文档中可以看到:

如果字段在内容没有改变的情况下失去焦点,则不会触发事件。要手动触发事件,请应用不带参数的.change():

$("#select_id").val("val2").change();

更多信息请参见.change()。

我需要选择一个选项,但两个选项可能具有相同的值。 这纯粹是为了视觉(前端)的差异。 你可以选择一个选项(即使两个值相同),如下所示:

let options = $('#id_100 option')
options.prop('selected', false)   // Deselect all currently selected ones
let option = $(options[0])        // Select option from the list
option.prop('selected', true)
option.parent().change()          // Find the <select> element and call the change() event.

这将取消当前选中的所有<option>元素。选择第一个元素(使用选项[0]),并使用change事件更新<select>元素。