How can I dynamically make a select2 combobox read-only?
Here's what I've tried so far:
$('...').attr({'readonly': 'readonly'}).trigger('change.select2'); $('...').attr({'readonly': 'readonly'}).trigger('change'); $('...').select2().enable(false);
$(element). select2('destroy'). attr("readonly", true)
According to HTML specs, the select tag in HTML doesn't have a readonly attribute, only a disabled attribute. So if you want to keep the user from changing the dropdown, you have to use disabled .
In order to enable or disable Select2, you should call . prop('disabled', true/false) on the element. Support for the old methods will be completely removed in Select2 4.1.
Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results. 25k. https://select2.org. Tags: select, jquery, autocomplete, typeahead, dropdown, ui, multiselect, tag, tagging.
This is Solution for Latest select2
(Tested With 4.0.7
) using css only
/*Select2 ReadOnly Start*/ select[readonly].select2-hidden-accessible + .select2-container { pointer-events: none; touch-action: none; } select[readonly].select2-hidden-accessible + .select2-container .select2-selection { background: #eee; box-shadow: none; } select[readonly].select2-hidden-accessible + .select2-container .select2-selection__arrow, select[readonly].select2-hidden-accessible + .select2-container .select2-selection__clear { display: none; } /*Select2 ReadOnly End*/
See: http://select2.github.io/select2/
I did it with:
$("#modelname-fieldname").select2({disabled:'readonly'});
Where:
modelname-fieldname
is as in: $form -> field($modelname, "fieldname") -> widget(Select2::classname(), [ ... ]);
readonly
is true, false or a string readonly
Optionally you can change the cursor when hovering over the select2
field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With