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

其他回答

我已经准备了一个小的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();

当值是ID而文本是代码时,我遇到了一个问题。不能使用代码设置值,但不能直接访问ID。

var value;

$("#selectorId > option").each(function () {
  if ("SOMECODE" === $(this).text()) {
    value = $(this).val();
  }
});

//Do work here
var opt = new Option(name, id);
$("#selectboxName").append(opt);
opt.setAttribute("selected","selected");

选择值为'val2'的选项:

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

这肯定适用于选择控件:

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