Limit Select2 to one selection per optgroup with multiple selection

Here is a example to create multiple select with grouped multiple select where you can select one option per group.

HTML code

<pre class="wp-block-syntaxhighlighter-code">
&amp;lt;select multiple style=&quot;width: 300px&quot;&gt;
  &amp;lt;optgroup label=&quot;Alaskan/Hawaiian Time Zone&quot;&gt;
    &amp;lt;option groupid=&quot;a&quot; value=&quot;AK&quot;&gt;Alaska&amp;lt;/option&gt;
    &amp;lt;option groupid=&quot;a&quot; value=&quot;HI&quot;&gt;Hawaii&amp;lt;/option&gt;
  &amp;lt;/optgroup&gt;
  &amp;lt;optgroup label=&quot;Pacific Time Zone&quot;&gt;
    &amp;lt;option groupid=&quot;b&quot; value=&quot;CA&quot;&gt;California&amp;lt;/option&gt;
    &amp;lt;option groupid=&quot;b&quot; value=&quot;NV&quot;&gt;Nevada&amp;lt;/option&gt;
    &amp;lt;option groupid=&quot;b&quot; value=&quot;OR&quot;&gt;Oregon&amp;lt;/option&gt;
    &amp;lt;option groupid=&quot;b&quot; value=&quot;WA&quot;&gt;Washington&amp;lt;/option&gt;
  &amp;lt;/optgroup&gt;

&amp;lt;/select&gt;
</pre>

JavaScript Code


$(function() {
    $('select').select2({
      allowClear: true,
      placeholder: "Pick a State"
    });

    //Select2 Event handler for selecting an item
    $('select').on("select2:selecting", function(evt, f, g) {
      disableSel2Group(evt, this, true);
    });

    // Select2 Event handler for unselecting an item
    $('select').on("select2:unselecting", function(evt) {
      disableSel2Group(evt, this, false);
    });
  });


  // At some point during the select2 instantation it created the 
  // data object it needs with the source select option.
  // This function, called by the events above to set the current status for the
  // group for which the selected option belongs.
  function disableSel2Group(evt, target, disabled) {
    // Found a note in the Select2 formums on how to get the item to be selected

    var selId = evt.params.args.data.id;
    var group = $("option[value='" + selId + "']").attr("groupid");

    var aaList = $("option", target);
    $.each(aaList, function(idx, item) {
      var data = $(item).data("data");

      var itemGroupId = $("option[value='" + data.id + "']").attr("groupid");
      if (itemGroupId == group && data.id != selId) {
        data.disabled = disabled;
      }
    })
  }

Check demo here



The following two tabs change content below.
Umar Farooque Khan is Software developer and professional blogger serving Worldwide on freelancer and ODesk platform to show the capability of his skills. He is the founder of pTutorial.com. The main purpose of this site is sharing and exchanging of Knowledge related to the recent technologies.