Hitesh Patel
Hitesh Patel

Reputation: 53

Select2 dropdown on disabled mode

I have the following issue:

Fiddle Link

<select id="select2" style="width:250px">
  <option value=""></option>
  <option value="option 1">Option 1</option>
  <option value="option 2">Option 2</option>
  <option value="option 3">Option 3</option>
</select>

<input id="disableBtn" type="button" value="Disable" />

<input id="enableBtn" type="button" value="Enable" />

While select box is disabled, the drop down still pops up if spacebar is hit after focus on select box.

Following is the js code:

$('#select2').select2({placeholder: 'Select an option',minimumResultsForSearch: 'Infinity'});
$('#disableBtn').on('click', () => {$('#select2').attr('disabled', 'true');});
$('#enableBtn').on('click', () => {$('#select2').removeAttr('disabled');});

Upvotes: 5

Views: 5446

Answers (1)

beaver
beaver

Reputation: 17647

I think there is an issue on select2 jQuery component. So here is a snippet which adopt a workaround to achieve your goal:

$('#myselect').select2({
  containerCssClass: 'mysel-con',
  placeholder: 'Select an option',
  minimumResultsForSearch: 'Infinity'
});

$('#disableBtn').on('click', ()=>{
  $('#myselect').select2('enable', false);
  $('.mysel-con').css('pointer-events', 'none');
});

$('#enableBtn').on('click', ()=>{
  $('#myselect').select2('enable');
  $('.mysel-con').css('pointer-events', '');
});
<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.full.min.js"></script>

<select id="myselect" style="width:250px">
  <option value=""></option>
  <option value="option 1">Option 1</option>
  <option value="option 2">Option 2</option>
  <option value="option 3">Option 3</option>
</select>

<input id="disableBtn" type="button" value="Disable" />

<input id="enableBtn" type="button" value="Enable" />

containerCssClass option is used to define a css class used as a jQuery selector for select2 container.

So adding CSS property pointer-events: none to this container the goal is reached.

Pay attention to use select2.full version (see. https://github.com/select2/select2/tree/master/dist/js).

Fiddle updated.

Upvotes: 3

Related Questions