How to initialize a select2 disabled

DonJuwe picture DonJuwe · Aug 4, 2014 · Viewed 17.9k times · Source

I have a simple select2 init which I want to be disabled by default without chaining a .select2("enable", false) afterwards.

HTML:

<input type='hidden' value="192" data-init-text='Bla bla' name="input" id="test" style="width:300px;" />

JS:

$(document).ready(function() {
    $('#test').select2({
        minimumInputLength: 3,
        placeholder: "Search",
        enable: "false", // I want this to be working!
        ajax: {
            url: "http://www.weighttraining.com/sm/search",
            dataType: 'jsonp',
            quietMillis: 100,
            data: function(term, page) {
                return {
                    types: ["exercise"],
                    limit: -1,
                    term: term
                };
            },
            results: function(data, page ) {
                return { results: data.results.exercise }
            }
        },
        formatResult: function(exercise) { 
            return "<div class='select2-user-result'>" + exercise.term + "</div>"; 
        },
        formatSelection: function(exercise) { 
            return exercise.term; 
        },
        initSelection : function (element, callback) {
            var elementText = $(element).attr('data-init-text');
            callback({"term":elementText});
        }
    });
});

See my JSFiddle for an example. Select2 Docs here.

Answer

Jul13nT picture Jul13nT · Aug 4, 2014

Simply add the disabledattribute to your input.

<input disabled type='hidden' value="192" data-init-text='Bla bla' name="input" id="test" style="width:300px;" />

$(document).ready(function() {
    $('#test').select2({
        minimumInputLength: 3,
        placeholder: "Search",
        ajax: {
            url: "http://www.weighttraining.com/sm/search",
            dataType: 'jsonp',
            quietMillis: 100,
            data: function(term, page) {
                return {
                    types: ["exercise"],
                    limit: -1,
                    term: term
                };
            },
            results: function(data, page ) {
                return { results: data.results.exercise }
            }
        },
        formatResult: function(exercise) { 
            return "<div class='select2-user-result'>" + exercise.term + "</div>"; 
        },
        formatSelection: function(exercise) { 
            return exercise.term; 
        },
        initSelection : function (element, callback) {
            var elementText = $(element).attr('data-init-text');
            callback({"term":elementText});
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.2.0/select2.min.js"></script>
<input disabled type='hidden' value="192" data-init-text='Bla bla' name="input" id="test" style="width:300px;" />