sasori
sasori

Reputation: 5463

how to check if variable value is one of the options in select2 when it opens?

how to detect if my variable value does exist in one of the options inside the select2 ? e.g I want to remove that option from the selections if it does exist once the select2 opens.

so far, I only have a condition to detect if the select2 is open, so how to check if my var does exist inside the options?

var myvariable = $('form#myform #toremove').val();
$('form#myform .select2').on('select2:open', function(e){
   //this part is wrong
   $('form#myform .select2 option').each(function(){
       if($(this).val() == myvariable){
           $(this).remove();
       }
   }); 
});

Upvotes: 0

Views: 2425

Answers (2)

Dekel
Dekel

Reputation: 62626

You can check the <option> elements when the menu is opened, and remove the relevant elements from the DOM:

$(document).ready(function() {
  $("#s1").select2();

  
  $("#s1").on('select2:opening', function (e, i) {
    $(this).find('option').each(function(i, e) {
      // You can check either the text or the value
      if ($(this).text() == 'Alabama' || $(this).val() == 'AL') {
        $(this).remove();
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script>

<select id="s1" multiple="multiple" width="100">
  <option value="AL">Alabama</option>
  <option value="WY">Wyoming</option>
</select>

Upvotes: 2

Daren Delima
Daren Delima

Reputation: 131

Remove it directly after opening

$('.select2 option[value="'+myvariable+'"]').remove()

Upvotes: 0

Related Questions