JSFiddle - React, Tailwind, and code Playground

by koh_edwin

HTML

<!DOCTYPE html>
<html>
<head>

</head>

<body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" />
<div id="select-container">
  <select id="select-test" multiple="multiple" style="width:300px">
    <option>Canada</option>
    <optgroup label="Alberta">
        <option>Alberta</option>
        <option>Calgary Zone</option>
        <option>Central Zone (Alta.)</option>
        <option>Edmonton Zone</option>
        <option>North Zone</option>
        <option>South Zone</option>
                          
    </optgroup>
    <optgroup label="British Columbia">
        <option>British Columbia</option>
        <option>Fraser Health</option>
        <option>Interior Health</option>
        <option>Island Health</option>
        <option>Northern Health</option>
        <option>Vancouver Coastal Health</option>

    </optgroup>
  </select>
</div>

</body>
</html>

JavaScript

$("#select-test").select2({closeOnSelect:false});

    let optgroupState = {};
    
    $("body").on('click', '.select2-container--open .select2-results__group', function() {
      $(this).siblings().toggle();
      let id = $(this).closest('.select2-results__options').attr('id');
      let index = $('.select2-results__group').index(this);
      optgroupState[id][index] = !optgroupState[id][index];
    })
    
    $('#select-test').on('select2:open', function() {
      $('.select2-dropdown--below').css('opacity', 0);
      setTimeout(() => {
        let groups = $('.select2-container--open .select2-results__group');
        let id = $('.select2-results__options').attr('id');
        if (!optgroupState[id]) {
          optgroupState[id] = {};
        }
        $.each(groups, (index, v) => {
          optgroupState[id][index] = optgroupState[id][index] || false;
          optgroupState[id][index] ? $(v).siblings().show() : $(v).siblings().hide();
        })
        $('.select2-dropdown--below').css('opacity', 1);
      }, 0);
    })