javascripthtmljqueryhtml-selectoptgroup

Check if some or all options in optgroup selected


I have a dropdown that's being dynamically generated from JSON. The format is like this:

<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>

I'm trying to figure out if all options in the optgroup have been selected. From here, I'm going to generate a string dependent if all options have been selected or just a few in the optgroup, so if the whole US is selected:

country = {[US]}

If only TN and MS are selected:

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

My first attempt was something like this:

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

This didn't work for me for some reason.

edit: If I selected two states say TN and AL, it would return statelist: [Obj obj]


Solution

  • You have to do a bit more checking to see if all are selected or not:

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