Punit Gajjar Punit Gajjar - 26 days ago 8
Javascript Question

Don't allow to select other option if selected specific value with select2

As you can see i have select box with the select2 (multiple) select feature, with some option like

<option value="All"> All </option>
<option value="test@email.com"> User 1</option>
<option value="test2@email.com"> User 2 </option>
<option value="Test3@rmail.com"> User 3 </option>


is that possible that if i choose the option
All
from the select box then select box dose't not allow me to choose the other option from the given options until and unless i remove it.

I want to restrict the user to select either choose
All
or select the multiple users from the options.

i am ready to use jQuery or javascript to achieve this.

Answer

Working fiddle.

You could set the value of select to All when the option All is presented :

$("#my-select").select2();

$("#my-select").on('change', function(){
    var selected = $(this).val();

    if(selected != null)
    {
      if(selected.indexOf('All')>=0){
          $(this).val('All').select2();
      }
    }
})

Hope this helps.

$("#my-select").select2();

$("#my-select").on('change', function(){
  var selected = $(this).val();

  if(selected != null)
  {
    if(selected.indexOf('All')>=0){
      $(this).val('All').select2();
    }
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.min.js"></script>

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.css" rel="stylesheet"/>

<select multiple id="my-select" style="width:300px">
  <option value="All"> All </option>
  <option value="test@email.com"> User 1</option>
  <option value="test2@email.com"> User 2 </option>
  <option value="Test3@rmail.com"> User 3 </option>
</select>

Comments