Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2: Hide certain options dynamically

Basically what I'm looking for is the ability to hide options from the dropdown of select items. So, technically they would still be options, but you just wouldn't be able to click them since they're hidden.

I've looked through the docs and have found things related to disabling, unfortunately I very specifically want the ability to hide items. Does anyone have advice on how to accomplish this?

Were it possible to do something like have the select do some specific mapping between the original <option> element and the select2 copy of that element, that would work as well. As an example, say, "if the original <option> has such class or has such attribute, the resulting item in the select dropdown will be constructed this way".

like image 249
jacheson Avatar asked Jul 31 '14 16:07

jacheson


2 Answers

Would adding the following CSS Rule to the page solve your problem?

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

Basically it would hide a disable option instead of displaying it with a gray background.

Use disabled instead of display:'none' in your options list also.

JS Bin

like image 182
John Avatar answered Oct 01 '22 18:10

John


I just invested 3 hours and found a very clean and easy solution for me dynamically showing/hiding options in a select2-container.

First, I create the select2 with this option:

$( selector ).select2({   templateResult: resultState }); 

Then I provide the resultState callback function which copies all classes from the original <option> to the select2-option. This allows us to show/hide options in select2 depending on the class we assign to the original option.

function resultState(data, container) {     if(data.element) {         $(container).addClass($(data.element).attr("class"));     }     return data.text; } 

In my css I declared this line:

.select2-container .select2-results__option.optInvisible {     display: none; } 

Now I can easy show or hide hide any options in the select2-container by adding the optInvisible class to the <option>:

<select>   <option class="optInvisible">Choose one</option>   <option value="1">1</option> </select> 

Or you could also update it dynamically using addClass("optInvisible") or removeClass("optInvisible").

May this helps anyone ;) Greetings

like image 34
Peter Schilling Avatar answered Oct 01 '22 19:10

Peter Schilling