$(function() {
var theData = [{
"id": "",
"text": ""
},
{
"text": "Group 1",
"children": [{
"id": 1,
"text": "Option 1.1"
},
{
"id": 2,
"text": "Option 1.2"
}
]
},
{
"text": "Group 2",
"children": [{
"id": 3,
"text": "Subgroup 2.1",
"children": [{
"id": 41,
"text": "Option 2.1.1"
},
{
"id": 42,
"text": "Option 2.1.2"
}
]
},
{
"id": 4,
"text": "Subgroup 2.2",
"children": [{
"id": 41,
"text": "Subgroup 2.2.1",
"children": [{
"id": 41,
"text": "Option 2.2.1.1"
}]
},
{
"id": 42,
"text": "Subgroup 2.2.2",
"children": [{
"id": 41,
"text": "Option 2.2.2.1"
},
{
"id": 42,
"text": "Option 2.2.2.2"
}
]
}
]
}
]
}
];
$("#mySelect").select2({
placeholder: "Select a option...",
data: theData
});
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css">
<select id="mySelect" class="form-control" style="width:400px;"></select>
<br>
<hr>
<br>
Notice how these nested optgroups are rendered as if they weren't nested at all. They are all only one level deep:<br>
<select>
<option value="" data-select2-id="1"></option>
<optgroup label="Group 1" data-select2-id="2">
<option value="1" data-select2-id="3">Option 1.1</option>
<option value="2" data-select2-id="4">Option 1.2</option>
</optgroup>
<optgroup label="Group 2" data-select2-id="5">
<optgroup label="Subgroup 2.1" data-select2-id="6">
<option value="41" data-select2-id="7">Option 2.1.1</option>
<option value="42" data-select2-id="8">Option 2.1.2</option>
</optgroup>
<optgroup label="Subgroup 2.2" data-select2-id="9">
<optgroup label="Subgroup 2.2.1" data-select2-id="10">
<option value="41" data-select2-id="11">Option 2.2.1.1</option>
</optgroup>
<optgroup label="Subgroup 2.2.2" data-select2-id="12">
<option value="41" data-select2-id="13">Option 2.2.2.1</option>
<option value="42" data-select2-id="14">Option 2.2.2.2</option>
</optgroup>
</optgroup>
</optgroup>
</select>