You can listen for the select2:unselecting
event and cancel it if the item being unselected is one you want to keep. However, those items will still have the “x” icon in them, so I think the user interface will be confusing.
You could use some CSS to remove those icons. For example, if one of the selections you want to keep has the label “ABC”, you can use the following CSS to remove the “x” for that item:
.select2-selection__choice[title="ABC"] .select2-selection__choice__remove {
display: none;
}
However, if the values you want to keep are dynamic (so you can’t hard-code them into your CSS), you can use JavaScript to remove them:
var itemsToKeep = ['ABC', 'DEF', ...];
for (var i = 0; i < itemsToKeep.length; i++) {
var selectItem = '.select2-selection__choice[title="' +
itemsToKeep][i] +'"] > .select2-selection__choice__remove';
$(selectItem).remove();
That will remove the “x” from those items you want to keep. However, the items in the results list (the dropdown) will still be shown as selected, and you can unselect them by clicking on them. So you will probably also need to listen for the “select2:unselecting” event and cancel it if it was fired on one of the items you want to keep. (You cancel the event by calling preventDefault()
on the Event object that is passed to your event handler.) For example:
var itemsToKeep = ["ABC", "DEF", ...];
$('#my_select').on('select2:unselecting', function(event) {
if (itemsToKeep.indexOf(event.params.data.text) > -1) {
event.preventDefault();
}
}
Note that the event passed to your handler includes a params
property which is an object that contains the data for the selected item.