Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding Select2 options

I'm trying to hide some of the Select2 options, but when I do something like this:

<option style="display: none;">...</option>

Select2 ignores it, unlike when I disable an option, or make it "readonly".

Any ideas?

like image 999
Tomer Amir Avatar asked Mar 03 '14 09:03

Tomer Amir


2 Answers

I stumbled upon this subject when looking for an answer to the same problem and i resolved it using the 'templateResult' callback of select2.

<select id="mySelect">
  <option value="1" data-show="1">1</option>
  <option value="2">2</option> <!-- option i want to hide -->
</select>

At the initialization of my select2 :

var dataIWantToShow = '1';
$('#mySelect').select2({
    templateResult: function(option) {
        var myOption = $('#mySelect').find('option[value="' + option.id + '"');
        if (myOption.data('show') == dataIWantToshow) {
            return option.text;
        }
        return false;
    }
});

To avoid having empty li displayed in the select2 list of options i added the following css :

li.select2-results__option:empty {
    display: none;
}

This solution does not add or remove options from the original select.

working fiddle

like image 85
Jorigole Avatar answered Oct 22 '22 16:10

Jorigole


I resolved this problem with an epic solution.

My version of select2 is 4.0.5 and only requires using the hidden property (you can change its logic) in each hidden options, without requiring style="display:none" (more clean for me).

<select class="select2">
   <option value="">Select</option>
   <option value="1">One</option>
   <option value="2" hidden>Two</option>
   <option value="3">One</option>
</select>

Right now, the only code needed is in the initialization of select2:

$('.select2').select2({
   templateResult: function(option) {
      if(option.element && (option.element).hasAttribute('hidden')){
         return null;
      }
      return option.text;
   }
});

hidden is a standard property and you can dynamicaly change it with attr and removeAttr jQuery methods: https://www.w3schools.com/tags/att_global_hidden.asp

like image 43
Eng. Ariel Grassano Avatar answered Oct 22 '22 16:10

Eng. Ariel Grassano