Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide selected items in select2

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.

like image 577
Ido Ran Avatar asked Nov 28 '22 13:11

Ido Ran


2 Answers

Just apply this CSS.

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

Small Update for recent versions :

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

Source

like image 197
Satheez Avatar answered Dec 06 '22 00:12

Satheez


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.

like image 36
rmwever Avatar answered Dec 05 '22 23:12

rmwever