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

cli*_*bak 4 javascript jquery html5 html-select

所以我正在编写一个需要输入地址的应用程序,我有一个select元素供用户选择州/省.它需要支持US,Canada所以它嵌套optgroups了将那些out和单个第一级选项分开,因为它是默认值.这是一个基本的例子:

<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>
Run Code Online (Sandbox Code Playgroud)

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

$("#state").val(myValue)
Run Code Online (Sandbox Code Playgroud)

而且我知道您可以通过这种方式基于文本设置选项

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

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

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

$element
Run Code Online (Sandbox Code Playgroud)

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

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

asg*_*ant 24

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

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

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

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


cli*_*bak 15

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

$("#state option").filter(
  // filter function
).prop('selected', true);
Run Code Online (Sandbox Code Playgroud)

经过大量的尝试,我得到了它,它的工作原理:

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


blu*_*fus 7

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

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

$("#state").val( a_value );
Run Code Online (Sandbox Code Playgroud)