jQuery - 使用嵌套在 optgroups 中的选项的值或文本设置选择框的选定选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17869144/
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 20:06:56  来源:igfitidea点击:

jQuery - Set the selected option of a select box using value or text with options nested in optgroups

javascriptjqueryhtmlhtml-select

提问by climbak

So I am writing an app that requires an address input and I have a selectelement for the user to select the state/province. It needs to support the USand Canadaso it has nested optgroupsto separate those out and a single, first level option as it's default value. Here is a basic example:

所以我正在编写一个需要地址输入的应用程序,我有一个select元素供用户选择州/省。它需要支持USCanada因此它嵌套optgroups以将它们分开,并将单个第一级选项作为默认值。这是一个基本示例:

<select name="state" id="state">
  <option class="co" value="" data-placeholder="true" disabled selected>Choose your state...</option>
  <optgroup label="United States">
    <option class="co" value="AL">Alabama</option>
    <option class="co" value="AK">Alaska</option>
    <option class="co" value="AZ">Arizona</option>
  </optgroup>
  <optgroup label="Canada">
    <option class="co" value="AB">Alberta</option>
    <option class="co" value="BC">British Columbia</option>
    <option class="co" value="MB">Manitoba</option>
  </optgroup>

Now I need to programmatically select the option that matches input from an external source and I want to check for a match based on both the value of the option element or its text. Whichever option is a match would then be set as the selected option. I know you can set the selected option by value using

现在我需要以编程方式选择与来自外部源的输入匹配的选项,并且我想根据选项元素的值或其文本检查匹配项。任何匹配的选项都将被设置为选定的选项。我知道您可以使用

$("#state").val(myValue)

and I know you can set an option based on text in this way

我知道你可以通过这种方式设置基于文本的选项

var myText = "The state I want.";
$("#state").children().filter(function() {
  return $(this).text() == myText;
}).prop('selected', true);

Is there a clean way to do this without having to run through each child and checking if it's an optgroup and then running through all its children to check for a match? Is there an easy way through jQuery to combine the value and text methods of setting the selected option?

有没有一种干净的方法来做到这一点,而不必遍历每个子项并检查它是否是一个 optgroup,然后遍历其所有子项以检查匹配?是否有一种简单的方法通过 jQuery 来组合设置所选选项的值和文本方法?

One other complication, I am going to be doing this within an external jQuery plugin. Within the function I need to modify I have the select element as a variable

另一个复杂问题,我将在外部 jQuery 插件中执行此操作。在我需要修改的函数中,我将选择元素作为变量

$element

so I need a way to do it kind of like this if possible:

所以如果可能的话,我需要一种方法来做到这一点:

$element.descendents(":option").filter(function() {
  //do the selecting here
}).prop('selected', true);

回答by asgallant

If you want to select by the option value, use the value selector:

如果要按选项值进行选择,请使用值选择器:

var myText = "AZ";
$('#state option[value="' + myText + '"]').prop('selected', true);

If you want to search by the option's label, use a filter:

如果要按选项的标签进行搜索,请使用过滤器:

var myText = "Arizona";
$('#state option').filter(function () { return $(this).html() == myText; }).prop('selected', true)

回答by climbak

Solved. Since I already had my element passed to a function as a jQuery variable, $element, I couldn't just use the standard selector in the form of:

解决了。由于我已经将元素作为 jQuery 变量 $element 传递给函数,因此我不能仅使用以下形式的标准选择器:

$("#state option").filter(
  // filter function
).prop('selected', true);

After a lot of trying, I got this and it works:

经过多次尝试,我得到了这个并且它有效:

function functionIHadToChange($element, value) {
  // other code
  $element.find("option").filter(function(){
      return ( ($(this).val() == value) || ($(this).text() == value) )
    }).prop('selected', true);
}

回答by blurfus

I am not sure I understood completely your question but I am attempting to answer it in this fiddle

我不确定我是否完全理解你的问题,但我试图在这个小提琴中回答它

The trick being that you can select it by setting the value of the select box directly

诀窍是您可以通过直接设置选择框的值来选择它

$("#state").val( a_value );

回答by varadha

You can set it by $("#select_id").prop("selectedIndex", 3); // Select index starts from zero.

你可以通过 $("#select_id").prop("selectedIndex", 3); // Select index starts from zero.

Read here for example this.

在这里阅读例如这个

回答by Pran

I'm late here but for future visitor, easiest way to do that is :

我来晚了,但对于未来的访客,最简单的方法是:

html

html

<select name="dept">
<option value="">This doctor belongs to which department?</option>
<option value="1">Orthopaedics</option>
<option value="2">Pathology</option>
<option value="3">ENT</option>
</select>

jQuery

jQuery

$('select[name="dept"]').val('3');

Output: This will active ENT.

输出:这将激活ENT

回答by Manuel G?rlich

$element = $('select#state');
$options = $element.find('option');
$wanted_element = $options.filter(function () {
  return $(this).val() == "Alabama" || $(this).text() == "Alabama"
});
$wanted_element.prop('selected', true);

Would be one way to do it.

将是一种方法。

But i would guess, without knowing the exact internas of the .find()method, in the end jQuery will use at least two loops itself to perform this...

但我猜想,在不知道该.find()方法的确切内部结构的情况下,最终 jQuery 将使用至少两个循环本身来执行此操作...