Select2 v4.0 make optgroups selectable


I'm using the latest version of select2 (4.0.0) and I can't find the option to make optgroups selectable.

An optgroup is used to group different options of the dropdown, as shown in their basic examples:
Example for an optgroup

I need this optgoup to be selectable too! It was possible in 3.5.1 but it isn't the default setting in 4.0.0 anymore.

My Code Looks like this:

$(document).ready(function() {
     data: [{
       text: "group",
       "id": 1,
       children: [{
         "text": "Test 2",
         "id": "2"
       }, {
         "text": "Test 3",
         "id": "3",
         "selected": true
<script src=""></script>
<script src=""></script>
<link href="" rel="stylesheet" />

<select id="countrySelect" style="width: 380px;" placeholder="Select regions..."></select>

Best Solution

This was requested over on GitHub, but realistically it is not actually possible. It was previously possible with a <input />, but the switch to a <select> meant that we now explicitly disallow a selectable <optgroup>.

There is a technical barrier here that Select2 will likely never be able to tackle: A standard <optgroup> is not selectable in the browser. And because a data object with children is converted to an <optgroup> with a set of nested <option> elements, the problem applies in your case with the same issue.

The best possible solution is to have an <option> for selecting the group, like you would have with a standard select. Without an <option> tag, it's not possible to set the selected value to the group (as the value doesn't actually exist). Select2 even has a templateResult option (formatResult in 3.x) so you can style it as a group consistently across browsers.