Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 - make it readonly (not disabled!) from js

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); 
like image 970
Catalin Avatar asked Jan 23 '17 13:01

Catalin


People also ask

How do I set select2 to readonly?

$(element). select2('destroy'). attr("readonly", true)

How do I make a select tag readonly?

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 .

How do I turn off Select 2?

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.

What is select2 full min JS?

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.


2 Answers

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*/ 
like image 133
Ali Jamal Avatar answered Oct 14 '22 09:10

Ali Jamal


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.

like image 31
Cas Knook Avatar answered Oct 14 '22 09:10

Cas Knook