4
votes

I'm trying to use select2 jQuery plugin to enhance a select element in HTML app. The select allow to choose multiple items.

I'll like to remove the items that are currently selected from the dropdown. I didn't find explicit solution in the docs.

The current solution I've found was to use templateResult option and have the template function return null if the item is selected. This cause Results.prototype.template function to set container.style.display = 'none' but this has the side-effect of causing the keyboard to still select those items even though they are not visible.

4

4 Answers

19
votes

Just apply this CSS.

.select2-results__option[aria-selected=true] { display: none;}

Small Update for recent versions :

.select2-results__option--selected { display: none;}

Source

3
votes

Check out the answer provided here, provided by Hakam Fostok.

I've reproduced his answer below here for completeness:

my solution was modified the select2.js (the core, version 4.0.3) in the line #3158. Add the following verification :

if ($option[0].selected == true) {
 return;
}

With this verification, we can exclude from the dropdown list, the selected ones. And if you write the name of a selected option, appear the text of option "noResult" .

Here the complete code:

SelectAdapter.prototype.query = function (params, callback) {
 var data = [];
 var self = this;`

 var $options = this.$element.children();`

 $options.each(function () {
  var $option = $(this);    

  if (!$option.is('option') && !$option.is('optgroup') ) {
   return;
  }

  if ($option[0].selected == true) {
   return;
  }

  var option = self.item($option);    
  var matches = self.matches(params, option);    

  if (matches !== null) {
   data.push(matches);
  }
 });

 callback({
  results: data
 });
};

For my purposes, I was using the select2.js file, so I made the change at line 3195.

1
votes

For versions 4 and 4.1

.select2-container--default .select2-results__option[aria-selected=true] {
    display: none !important;
}

Works fine!

0
votes

In addition to @Satheez answer, this script will let you maintain the placeholder after hiding all the selected items.

$('.selector').select2().on("change", function (e) {
    $('.select2-search__field').attr('placeholder', 'Here is your placeholder');
});