Search code examples
javascriptjqueryjquery-selectorsoptgroup

Select children of optgroup only on tag click


I am attempting to use an optgroup label to select all of the option in the group.

This is working fine, however, when I also select a group <option> it selects all optgroup elements. How do I make it so selection is based on only the optgrouptag?

$(document).ready(function() {
  $("optgroup").on("click", function() {
    $(this).children("option").prop("selected", true);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
  <optgroup label="Group1">
    <option value="11">Option 1</option>
    <option value="12">Option 2</option>
  </optgroup>
  <optgroup label="Group2">
    <option value="21">Option 1</option>
    <option value="22">Option 2</option>
  </optgroup>
</select>


Solution

  • check the tag name of the element since it will bubble.. loop thru each of the options and only check ones that are not checked.

    $(document).ready(function() {
      $("optgroup").on("click", function(e) {
        if(e.target.tagName === 'OPTGROUP'){
          $(this).children("option").each(function(){
            this.selected = !this.selected;
          });
        }
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select multiple size=6>
      <optgroup label="Group1">
        <option value="11">Option 1</option>
        <option value="12">Option 2</option>
      </optgroup>
      <optgroup label="Group2">
        <option value="21">Option 1</option>
        <option value="22">Option 2</option>
      </optgroup>
    </select>