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


当前回答

对我来说,下面的工作就完成了

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

其他回答

我已经准备了一个小的JQuery扩展,删除所有不必要的选项和隐藏所选的选项,用户只看到一个值在选择字段

$.prototype.makeReadOnly = function (canClick = false) {
    $(this).each(function () {
        $(this).readonly = true;
        if ($(this).is("select")) {
            if(!canClick) $(this).mousedown(function () { event.preventDefault(); }).keydown(function () { event.preventDefault(); });
            $(this).find('option:not(:selected)').remove();
            $(this).find('option').hide();
        }
    });
}

然后你可以让所有的选择都是只读的

$("select").makeReadOnly();

或者只选择特定的只读类

$("select.read-only").makeReadOnly();

最好的方法是这样的:

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

感谢傻瓜的回答:

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

$('.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#ddlCountry option').each(function () {
if ($(this).text().toLowerCase() == co.toLowerCase()) {
    this.selected = true;
    return;
} });

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

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>元素。