如何在 jQuery 的 SELECT 元素中选择特定选项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/314636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:56:46  来源:igfitidea点击:

How do you select a particular option in a SELECT element in jQuery?

jquery

提问by Jay Corbett

If you know the Index, Value or Text. also if you don't have an ID for a direct reference.

如果您知道索引、值或文本。如果您没有直接参考的 ID。

This, thisand thisare all helpful answers.

Thisthisthis都是有用的答案。

Example markup

示例标记

<div class="selDiv">
  <select class="opts">
    <option selected value="DEFAULT">Default</option>
    <option value="SEL1">Selection 1</option>
    <option value="SEL2">Selection 2</option>
  </select>
</div>

回答by Grastveit

A selector to get the middle option-element by value is

按值获取中间选项元素的选择器是

$('.selDiv option[value="SEL1"]')

For an index:

对于索引:

$('.selDiv option:eq(1)')

For a known text:

对于已知文本:

$('.selDiv option:contains("Selection 1")')

EDIT: As commented above the OP might have been after changing the selected item of the dropdown. In version 1.6 and higher the prop() method is recommended:

编辑:如上所述,OP 可能是在更改下拉列表的选定项目之后。在 1.6 及更高版本中,推荐使用 prop() 方法:

$('.selDiv option:eq(1)').prop('selected', true)

In older versions:

在旧版本中:

$('.selDiv option:eq(1)').attr('selected', 'selected')

EDIT2: after Ryan's comment. A match on "Selection 10" might be unwanted. I found no selectorto match the full text, but a filterworks:

EDIT2:在瑞安的评论之后。“选择 10”上的匹配可能是不需要的。我没有找到与全文匹配的选择器,但过滤器有效:

 $('.selDiv option')
    .filter(function(i, e) { return $(e).text() == "Selection 1"})

EDIT3: Use caution with $(e).text()as it can contain a newline making the comparison fail. This happens when the options are implicitly closed (no </option>tag):

EDIT3:小心使用,$(e).text()因为它可能包含使比较失败的换行符。This happens when the options are implicitly closed (no </option>tag):

<select ...>
<option value="1">Selection 1
<option value="2">Selection 2
   :
</select>

If you simply use e.textany extra whitespace like the trailing newline will be removed, making the comparison more robust.

如果您只是使用e.text任何额外的空格,如尾随换行符将被删除,使比较更加健壮。

回答by user1074546

None of the methods above provided the solution I needed so I figured I would provide what worked for me.

上面的方法都没有提供我需要的解决方案,所以我想我会提供对我有用的方法。

$('#element option[value="no"]').attr("selected", "selected");

回答by Leandro Ardissone

You can just use val()method:

你可以只使用val()方法:

$('select').val('the_value');

回答by mpoletto

By value, what worked for me with jQuery 1.7was the below code, try this:

根据价值,jQuery 1.7对我有用的是下面的代码,试试这个:

$('#id option[value=theOptionValue]').prop('selected', 'selected').change();

回答by Gone Coding

There are a number of ways to do this, but the cleanest approach has been lost among the top answers and loads of arguments over val(). Also some methods changed as of jQuery 1.6, so this needs an update.

有很多方法可以做到这一点,但最简洁的方法已经在顶级答案和大量争论中丢失了val()。从 jQuery 1.6 开始,一些方法也发生了变化,所以这需要更新。

For the following examples I will assume the variable $selectis a jQuery object pointing at the desired <select>tag, e.g. via the following:

对于以下示例,我将假设变量$select是指向所需<select>标签的 jQuery 对象,例如通过以下方式:

var $select = $('.selDiv .opts');

Note 1 - use val() for value matches:

注 1 - 使用 val() 进行值匹配:

For value matching, using val()is far simpler than using an attribute selector: https://jsfiddle.net/yz7tu49b/6/

对于值匹配,使用val()比使用属性选择器简单得多:https: //jsfiddle.net/yz7tu49b/6/

$select.val("SEL2");

The setter version of .val()is implemented on selecttags by setting the selectedproperty of a matching optionwith the same value, so works just fine on all modern browsers.

的 setter 版本.val()select通过将selected匹配的属性设置option为相同来在标签上实现的value,因此在所有现代浏览器上都可以正常工作。

Note 2 - use prop('selected', true):

注 2 - 使用 prop('selected', true):

If you want to set the selected state of an option directly, you can use prop(not attr) with a booleanparameter (rather than the text value selected):

如果要直接设置选项的选定状态,可以将prop(not attr) 与boolean参数(而不是文本值selected)一起使用:

e.g. https://jsfiddle.net/yz7tu49b/

例如https://jsfiddle.net/yz7tu49b/

$option.prop('selected', true);  // Will add selected="selected" to the tag

Note 3 - allow for unknown values:

注 3 - 允许未知值:

If you use val()to select an <option>, but the val is not matched (might happen depending on the source of the values), then "nothing" is selected and $select.val()will return null.

如果您使用val()选择<option>,但 val 不匹配(可能会发生取决于值的来源),则选择“无”$select.val()并将返回null

So, for the example shown, and for the sake of robustness, you could use something like this https://jsfiddle.net/1250Ldqn/:

因此,对于显示的示例,并且为了健壮性,您可以使用类似https://jsfiddle.net/1250Ldqn/ 的内容

var $select = $('.selDiv .opts');
$select.val("SEL2");
if ($select.val() == null) {
  $select.val("DEFAULT");
}

Note 4 - exact text match:

注 4 - 精确文本匹配:

If you want to match by exact text, you can use a filterwith function. e.g. https://jsfiddle.net/yz7tu49b/2/:

如果要按精确文本进行匹配,可以使用filterwith 函数。例如https://jsfiddle.net/yz7tu49b/2/

var $select = $('.selDiv .opts');
$select.children().filter(function(){
    return this.text == "Selection 2";
}).prop('selected', true);

although if you may have extra whitespace you may want to add a trim to the check as in

虽然如果您可能有额外的空格,您可能希望在检查中添加修剪

    return $.trim(this.text) == "some value to match";

Note 5 - match by index

注 5 - 按索引匹配

If you want to match by index just index the children of the select e.g. https://jsfiddle.net/yz7tu49b/3/

如果您想按索引匹配,只需索引选择的子项,例如https://jsfiddle.net/yz7tu49b/3/

var $select = $('.selDiv .opts');
var index = 2;
$select.children()[index].selected = true;

Although I tend to avoid direct DOM properties in favour of jQuery nowadays, to future-proof code, so that could also be done as https://jsfiddle.net/yz7tu49b/5/:

虽然我现在倾向于避免直接 DOM 属性而支持 jQuery,但为了面向未来的代码,也可以这样做https://jsfiddle.net/yz7tu49b/5/

var $select = $('.selDiv .opts');
var index = 2;
$select.children().eq(index).prop('selected', true);

Note 6 - use change() to fire the new selection

Note 6 - 使用 change() 来触发新的选择

In all the above cases, the change event does not fire. This is by design so that you do not wind up with recursive change events.

在上述所有情况下,更改事件都不会触发。这是设计使然,因此您不会以递归更改事件结束。

To generate the change event, if required, just add a call to .change()to the jQuery selectobject. e.g. the very first simplest example becomes https://jsfiddle.net/yz7tu49b/7/

如果需要,要生成更改事件,只需添加.change()对 jQueryselect对象的调用。例如,第一个最简单的例子变成了https://jsfiddle.net/yz7tu49b/7/

var $select = $('.selDiv .opts');
$select.val("SEL2").change();

There are also plenty of other ways to find the elements using attribute selectors, like [value="SEL2"], but you have to remember attribute selectors are relatively slow compared to all these other options.

还有很多其他方法可以使用属性选择器来查找元素,例如[value="SEL2"],但您必须记住,与所有这些其他选项相比,属性选择器相对较慢。

回答by Sandro

You could name the select and use this:

您可以命名选择并使用它:

$("select[name='theNameYouChose']").find("option[value='theValueYouWantSelected']").attr("selected",true);

It should select the option you want.

它应该选择您想要的选项。

回答by Jo?o Paulo Oliveira

   $(elem).find('option[value="' + value + '"]').attr("selected", "selected");

回答by Jay Corbett

Answering my own question for documentation. I'm sure there are other ways to accomplish this, but this works and this code is tested.

回答我自己的文档问题。我确信还有其他方法可以实现这一点,但是这可行并且此代码经过测试。

<html>
<head>
<script language="Javascript" src="javascript/jquery-1.2.6.min.js"></script>
<script type="text/JavaScript">

$(function() {
    $(".update").bind("click",      // bind the click event to a div
        function() {
            var selectOption = $('.selDiv').children('.opts') ;
            var _this = $(this).next().children(".opts") ;

            $(selectOption).find("option[index='0']").attr("selected","selected");
//          $(selectOption).find("option[value='DEFAULT']").attr("selected","selected");
//          $(selectOption).find("option[text='Default']").attr("selected","selected");


//          $(_this).find("option[value='DEFAULT']").attr("selected","selected");
//          $(_this).find("option[text='Default']").attr("selected","selected");
//          $(_this).find("option[index='0']").attr("selected","selected");

    }); // END Bind
}); // End eventlistener

</script>
</head>
<body>
<div class="update" style="height:50px; color:blue; cursor:pointer;">Update</div>
<div class="selDiv">
        <select class="opts">
            <option selected value="DEFAULT">Default</option>
            <option value="SEL1">Selection 1</option>
            <option value="SEL2">Selection 2</option>
        </select>
    </div>
</body>
</html>

回答by perumal N

Exactly it will work try this below methods

正是它会工作试试这个下面的方法

For normal select option

对于普通选择选项

<script>    
    $(document).ready(function() {
    $("#id").val('select value here');
       });
        </script>

For select 2 option triggeroption need to use

对于选择 2 选项触发选项需要使用

<script>    
        $(document).ready(function() {
        $("#id").val('select value here').trigger('change');
           });
            </script>

回答by Nick Tsai

For setting select value with triggering selected:

要在选择触发的情况下设置选择值:

$('select.opts').val('SEL1').change();


For setting option from a scope:

从范围设置选项:

$('.selDiv option[value="SEL1"]')
    .attr('selected', 'selected')
    .change();

This code use selector to find out the select object with condition, then change the selected attribute by attr().

此代码使用选择器找出具有条件的选择对象,然后通过 更改 selected 属性attr()



Futher, I recommend to add change()event after setting attribute to selected, by doing this the code will close to changing select by user.

此外,我建议change()在将属性设置为 后添加事件selected,通过这样做,代码将接近于更改用户选择。