jqueryhtmlhtml-selectoptgroup

jQuery - Click on optgroup selects all child options


How can I make an optgroup in a select tag clickable in html. When we click this label, all its child options should be selected.

Example: Selecting the optgroup with label Swedish Cars should automatically select the Volvo and Saab options.

<select>
  <optgroup label="Swedish Cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup label="German Cars">
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </optgroup>
</select>

Solution

  • Select elements have a multiple attribute for selecting multiple values.

    Here is one possible solution.

    In this code, if you click on one of the option group label, all sub-options will be selected automatically.

    $("optgroup").on("click", function() {
        $(this).children("option").prop("selected", "selected");
        $(this).next().children("option").prop("selected", false);
        $(this).prev().children("option").prop("selected", false);
    });
    select {
      height: 150px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select multiple>
      <optgroup label="Swedish Cars">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
      </optgroup>
      <optgroup label="German Cars">
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
      </optgroup>
    </select>