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

Catalin picture Catalin · Jan 23, 2017 · Viewed 31.9k times · Source

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);

Answer

Ali Jamal picture Ali Jamal · Mar 5, 2019

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*/