检查optgroup中的部分或全部选项是否已选中

问题描述 投票:0回答:3

我有一个从JSON动态生成的下拉列表。格式如下:

<optgroup id="US" label="United States class="optiongroup>
  <option value="AS">American Samoa</option>
  <option value="AL">Alabama</option>
  ...
  <option value="VI">US Virgin Islands</option>
  <option value="UT">Utah</option>
<optgroup>
<optgroup id="CA" label="Canada" class="optiongroup">
  <option value="AB">Alberta</option>
  <option value="BC">British Columbia</option>
  ...
  <option value="QC">Quebec</option>
  <option value="YT">Yukon Territory</option>
</optgroup>

我想弄清楚是否已经选择了optgroup中的所有选项。从这里开始,如果选择了所有选项或者只选择了一些选项,我将生成一个依赖于字符串的字符串,所以如果选择了整个US:

country = {[US]}

如果仅选择TN和MS:

state = {country: US, statelist: [TN, MS]}

我的第一次尝试是这样的:

$(".optiongroup").each(function() {
  var optgroup = $(this);
  $(optgroup.children()).each(function () {
    if ($(this).is(':selected')) {
      statearray.push($(this).attr('value'));
      state_flag = 1; //see if state exists
    } else {
      country_flag = 0; //entire country not selected
  }
}

由于某种原因,这对我不起作用。

编辑:如果我选择两个状态说TN和AL,它将返回statelist:[Obj obj]

javascript jquery html option optgroup
3个回答
1
投票

您需要进行更多检查以查看是否已选中所有内容:

$(".optiongroup").each(function() {
    var options = $(this).children("option"),
        length = options.length;

    if (options.filter(":selected").length == length) {
        //all are selected, do something!
        country_flag = 1;
        return true; //continue
    } else {
        //Not all selected, so push states
        options.filter(":selected").each(function() {
            statearray.push(this.value);
        });
    }
});

0
投票

在您开始推送之前,看起来并不像您声明的那样将“statearray”声明为数组。 “state_flag”和“country_flag”相同。


0
投票

试试这个...希望它能奏效

$("#selectId").children('optgroup').each(function(){                                
    if($(this).children('option').length == $(this).children('option:selected').length){
        // do stuff here when all options were selected under an optgroup   
    }else{
        // do stuff here when all options were NOT selected under an optgroup
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.