Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 disable/enable specific option

Tags:

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.

like image 749
Madhukar Hebbar Avatar asked Jul 07 '15 06:07

Madhukar Hebbar


People also ask

How do I make Select2 disabled?

Disabling a Select2 control Select2 will respond to the disabled attribute on <select> elements. You can also initialize Select2 with disabled: true to get the same effect.

How do I add options in Select2?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data.text, data.id, false, false); $('#mySelect2').append(newOption).trigger('change');

What Select2 dropdown?

Select2 allows you to change the way that the dropdown works, allowing you to do anything from attach it to a different location in the document or add a search box. It is common for decorators to attach to the render and position methods to alter how the dropdown is altered and positioned.


1 Answers

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.

like image 160
CBroe Avatar answered Sep 29 '22 14:09

CBroe