Clearable selection in select


#1

Hi! Need help with this:
I have a combo with select2, and I need to set one option as cleaner. I mean, when you select that option, it should erase all your current selections (that appears on the input) and also set the combo as disabled.
Thanks!


#2
<select id="select" style="width: 40%" multiple="multiple">
			<option value="MX">Mexico</option>
			<option value="BL">Belgica</option>
			<option value="US">Estados unidos</option>
			<option value="BR">Brasil</option>
			<option value="CD">Canada</option>
        <option value="CN">Cleaner Option</option>
		</select>
This is my select, (a test one), and i'd need that when the "Cleaner Option" is selected, it should clean all the current selections, and also set all the options inside the combo to disabled.

#3

First I would ask why the “cleaner” feature needs to be exposed as an option in the Select2, instead of, say, a separate button in the UI. The UI pattern you have described is not common in the industry.

But if you insist on going forward with this UI pattern, then you can accomplish what you want by using an event handler on the change (or change.select2) event. In the event handler, you would check whether the selected item is the Cleaner option. If so, you would then iterate through the option children of the underlying HTML select, set the disabled property to true on each one and set the selected property to false. Finally, you will have to re-initialize the Select2 widget, because there is no other way to force the Select2 to recognize that the underlying HTML elements’ disabled properties have changed.