-1

I need to hide/show options from select2 multi-select

I have tried something like this but option Two is not hidden:

 $(document).ready(function() {
  $('#test').select2();
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
 <select id="test" multiple style="width:250px">
        <option value="1">One</option>
        <option value="2" style='display:none;'>Two</option>
        <option value="3">Three</option>
    </select>

I have added a jsfiddle: https://jsfiddle.net/sindhujagovindaraju/xpvt214o/738000/

3 Answers3

2

You have to use "disabled" instead of "display: none" and write css like below:

$(document).ready(function(){
    $("#test").select2();
});
.select2-container--default .select2-results__option[aria-disabled=true] { display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
 <select id="test" multiple style="width:250px">
        <option value="1">One</option>
        <option value="2" disabled>Two</option>
        <option value="3">Three</option>
 </select>
0

you can use below code:

option[value=2] {display: none;}

best if you add for each li element a css class/id dynamically and target them instead of value which might dynamic

ps: IE might be problematic a bit though Options with display:none not hidden in IE

Raphael
  • 770
  • 1
  • 7
  • 23
0
 .Select-input option:nth-child(4){display: none;}
Dnyanesh
  • 1
  • 1
  • yeah. no results :( – Sindhuja Govindaraju Sep 05 '18 at 07:46
  • In you case just try with ".Select-input option:nth-child(2){display: none;}" – Dnyanesh Sep 05 '18 at 08:23
  • 1
    While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Luca Kiebel Sep 05 '18 at 09:26