Select2 disable/enable specific option

Madhukar Hebbar picture Madhukar Hebbar · Jul 7, 2015 · Viewed 68.3k times · Source

I have a list which is of type select2.

<select id="list" class="form-control select2 select2-hidden-accessible" tabindex="-1" aria-hidden="true">
<optgroup label="Types">
<option value="None">None</option>
<option value="1">One</option>
<option value="2">Two</option>
</optgroup>
</select>

I want to disable option which is having value=1 so I did like this

$("#list>optgroup>option[value='1']").prop('disabled',true);
   Result:// <option value="1" disabled>One</option>

It is working fine;but if i want to re-enable disabled option i tried below codes but still the select2 option is disabled.

$("#list>optgroup>option[value='1']").prop('disabled',false);
$("#list>optgroup>option[value='1']").removeProp('disabled');
  Result://   <option value="1">One</option>

but strange is disabled property of the option is removed. but the select2 option remains disabled.

Not getting how to resolve this. Need help.

Update: If I check DOM of select2 it is having this property even after removing disabled.

<li class="select2-results__option" id="select2-template-type-list-result-4qd3-merge" role="treeitem" aria-disabled="true">One</li>

if i make aria-disabled="false" it will enable. not able to get what is the cause.

Answer

CBroe picture CBroe · Jul 7, 2015

Probably easiest way to achieve this, would be calling .select2(…) on the element again after changing the disabled attribute.

http://jsfiddle.net/xoxd2u15/

Since select2 replaces the original select field with custom HTML elements (and hides the original), and apparently does not “watch” the options of that original select element for changes in their disabled state constantly after invocation, you have to call it once more after changing the state, so that it reads the current attribute values from the original element’s options.