Punit Gajjar
Punit Gajjar

Reputation: 4997

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="[email protected]"> User 1</option>
<option value="[email protected]"> User 2 </option>
<option value="[email protected]"> 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.

Upvotes: 2

Views: 3253

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

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="[email protected]"> User 1</option>
  <option value="[email protected]"> User 2 </option>
  <option value="[email protected]"> User 3 </option>
</select>

Upvotes: 3

Related Questions