Notification texts go here Contact Us Buy Now!

How make select2 readonly?

## How to Make Select2 Readonly To make a Select2 element readonly, you can use the following methods: ### Method 1: Using the `disabled` Option ```html $('.js-example-basic-single').select2({ disabled: true }); ``` ### Method 2: Setting the `readonly` Attribute ```html $('select option:selected').attr('disabled','disabled'); ``` Note that this method will only work for older versions of Select2 (prior to v4). ### Method 3: Using the `enable` Method ```html $('select').select2().enable(false); ``` This method is the recommended way to disable a Select2 element in versions 4 and above. ### Method 4: CSS Hack You can also use a CSS hack to make a Select2 element appear readonly: ```css .select2-container.select2-container-disabled .select2-choice { background-color: #ddd; border-color: #a8a8a8; } ``` This method will make the Select2 element appear disabled, but it will still be possible to select options. ### Method 5: Using the `readonly` Property ```html $("select").prop("disabled", true); // instead of $("select").enable(false); ``` This method is the recommended way to disable a Select2 element in versions 4 and above. ### Method 6: Destroying and Recreating the Select2 Element ```html $('select').select2('destroy').attr("readonly", true); ``` This method will completely destroy the Select2 element and recreate it as a readonly element. ### Method 7: Using a Custom Event Listener ```html $('select[data-select2-id]').on('select2:opening', function (e) { if( $(this).attr('readonly') == 'readonly') { // Check if select tag is readonly. console.log( 'readonly, can't be open !' ); e.preventDefault(); $(this).select2('close'); return false; }else{ console.log( 'expandable/selectable' ); } }); ```

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.