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"> &lt;select multiple style="width: 300px"> &lt;optgroup label="Alaskan/Hawaiian Time Zone"> &lt;option groupid="a" value="AK">Alaska&lt;/option> &lt;option groupid="a" value="HI">Hawaii&lt;/option> &lt;/optgroup> &lt;optgroup label="Pacific Time Zone"> &lt;option groupid="b" value="CA">California&lt;/option> &lt;option groupid="b" value="NV">Nevada&lt;/option> &lt;option groupid="b" value="OR">Oregon&lt;/option> &lt;option groupid="b" value="WA">Washington&lt;/option> &lt;/optgroup> &lt;/select> </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