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

Check if some or all options in optgroup selected

本文关键字:全部 选项 optgroup 是否 检查      更新时间:2023-09-26

我有一个从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已被选中。从这里开始,我将生成一个字符串依赖于是否选中了所有选项,还是只选中了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]

你需要做更多的检查,看看是否全部被选中:

$(".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);
        });
    }
});

看起来不像您在开始压入之前将"statearray"声明为数组。"state_flag"answers"country_flag"也一样。"

试试这个…希望它能起作用

$("#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
    }
});