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.
Just apply this CSS.
.select2-results__option[aria-selected=true] { display: none;}
Small Update for recent versions :
.select2-results__option--selected { display: none;}
Source
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With