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


当前回答

您可以使用属性选择器[attributename=optionalvalue]选择任何属性及其值,因此在您的情况下,您可以选择该选项并设置所选属性。

$("div.id_100 > select > option[value=" + value + "]").prop("selected",true);

其中value是您希望通过的值。

如果您需要删除任何先前选择的值,就像多次使用这种情况一样,您需要稍微更改它,以便首先删除所选的属性

$("div.id_100 option:selected").prop("selected",false);
$("div.id_100 option[value=" + value + "]")
        .prop("selected",true);

其他回答

我认为最简单的方法是选择设置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);
    }
});

这肯定适用于选择控件:

$('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();

Use:

$("div.id_100 > select > option[value=" + value + "]").attr("selected",true);

这对我很有用。我使用这段代码来解析一个fancybox更新表单中的值,我的完整源代码来自app.js:

jQuery(".fancybox-btn-upd").click(function(){
    var ebid = jQuery(this).val();

    jQuery.ajax({
        type: "POST",
        url: js_base_url+"manajemen_cms/get_ebook_data",
        data: {ebookid:ebid},
        success: function(transport){
            var re = jQuery.parseJSON(transport);
            jQuery("#upd-kategori option[value="+re['kategori']+"]").attr('selected',true);
            document.getElementById("upd-nama").setAttribute('value',re['judul']);
            document.getElementById("upd-penerbit").setAttribute('value',re['penerbit']);
            document.getElementById("upd-tahun").setAttribute('value',re['terbit']);
            document.getElementById("upd-halaman").setAttribute('value',re['halaman']);
            document.getElementById("upd-bahasa").setAttribute('value',re['bahasa']);

            var content = jQuery("#fancybox-form-upd").html();
            jQuery.fancybox({
                type: 'ajax',
                prevEffect: 'none',
                nextEffect: 'none',
                closeBtn: true,
                content: content,
                helpers: {
                    title: {
                        type: 'inside'
                    }
                }
            });
        }
    });
});

我的PHP代码是:

function get_ebook_data()
{
    $ebkid = $this->input->post('ebookid');
    $rs = $this->mod_manajemen->get_ebook_detail($ebkid);
    $hasil['id'] = $ebkid;
    foreach ($rs as $row) {
        $hasil['judul'] = $row->ebook_judul;
        $hasil['kategori'] = $row->ebook_cat_id;
        $hasil['penerbit'] = $row->ebook_penerbit;
        $hasil['terbit'] = $row->ebook_terbit;
        $hasil['halaman'] = $row->ebook_halaman;
        $hasil['bahasa'] = $row->ebook_bahasa;
        $hasil['format'] = $row->ebook_format;
    }
    $this->output->set_output(json_encode($hasil));
}

没有任何理由去想太多。您所要做的就是访问和设置一个属性。就是这样。

好的,一些基本的DOM:

如果你在JavaScript中直接这样做,你会这样做:

window.document.getElementById('my_stuff').selectedIndex = 4;

但你不是用JavaScript,而是用jQuery。在jQuery中,你想要使用.prop()函数来设置属性,所以你会这样做:

$("#my_stuff").prop('selectedIndex', 4);

不管怎样,只要确保你的id是唯一的。否则,你会用头撞墙,想知道为什么这行不通。