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


当前回答

这肯定适用于选择控件:

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

其他回答

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

选择值为'val2'的选项:

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

下面是一个类似jQuery插件的简单函数。

    $.fn.selectOption = function(val){
        this.val(val)
        .find('option')
        .removeAttr('selected')
        .parent()
        .find('option[value="'+ val +'"]')
        .attr('selected', 'selected')
        .parent()
        .trigger('change');

        return this;
    };

你可以简单地做这样的事情:

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

使用这个的原因是因为您将所选语句更改为跨浏览器支持的DOM,也会触发更改,以便您可以捕获它。

它基本上是一种人类动作模拟。

感谢傻瓜的回答:

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

$('.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事件有界,它也不会给出一个无限循环。

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

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