JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<select id="select1a"></select>
<br>
<select id="select1b"></select>
<br>
<select id="select2a"></select>
<br>
<select id="select2b"></select>
<br>
CSS
select {
width: 100%;
}
.select2-results__option[aria-disabled=true] {
display: none;
}
JavaScript
function buildPills1() {
let opts = [{
id: "",
text: "",
enabled: true
}];
for (let i = 0; i < 3; i++) {
let grp = [];
for (let j = 0; j < 3; j++) {
grp.push({
id: "opt_" + i + "_" + j,
text: "Option " + i + " " + j,
enabled: true
});
}
opts.push({
text: "Group " + i,
children: grp
});
}
return opts;
}
function buildPills2() {
let opts = [{
id: "",
text: "",
enabled: true
}];
for (let i = 0; i < 6; i++) {
opts.push({
id: "opt" + i,
text: "Option " + i,
enabled: true
});
}
return opts;
}
$.fn.select2.defaults.set("allowClear", true);
$.fn.select2.defaults.set("closeOnSelect", true);
$.fn.select2.defaults.set("minimumResultsForSearch", 17);
$.fn.select2.amd.define('select2/data/customAdapter', ['select2/data/array', 'select2/utils'],
function(ArrayAdapter, Utils) {
function CustomDataAdapter($element, options) {
CustomDataAdapter.__super__.constructor.call(this, $element, options);
}
Utils.Extend(CustomDataAdapter, ArrayAdapter);
CustomDataAdapter.prototype.updateOptions = function() {
this.$element.find('option').each(function(idx, opt) {
$(opt).prop('disabled', Math.random() < .7);
});
};
return CustomDataAdapter;
});
$("#select1a").select2({
data: buildPills1(),
dataAdapter: $.fn.select2.amd.require('select2/data/customAdapter'),
placeholder: "Groups and custom adapter"
}).on('select2:opening', function(e) {
$(this).data("select2").dataAdapter.updateOptions();
});
$("#select1b").select2({
data: buildPills1(),
placeholder: "Groups without custom adapter"
}).on('select2:opening', function(e) {
$(this).find('option').each(function(idx, opt) {
$(opt).prop('disabled', Math.random() < .7);
});
});
$("#select2a").select2({
data: buildPills2(),
dataAdapter: $.fn.select2.amd.require('select2/data/customAdapter'),
placeholder: "No groups and custom...