1

I'm using the Select2 library to remote load data via ajax. However, I'd also like to provide a default option "all". Right now it's easy enough for me to augment the "results" array with an {name: 'All', id: 'all'} object, and I can make it so 'All' is initially selected, but what I want is that somebody sees 'All' as an option even before they've entered the minimum input length.

Is that possible? Does anybody know how to accomplish this?

1 Answer 1

4

NOTE: This answer applies to Select2 3.5.2 or earlier. The solution for Select2 4.0 would use a DataAdapter.

You can supply a custom query function. When implementing this function, you can use the Select2 ajax function since it is publicly exposed.

var ALL_OPTION = { id: 'ALL', text: 'All' };

$('#select').select2({
    _minimumInputLength: 2,
    _ajaxQuery: Select2.query.ajax({
        // Place all your ajax options here, as if you were using
        // the Select2 "ajax" option.
    }),
    query: function(options) {
        if (options.term.length >= this._minimumInputLength) {
            this._ajaxQuery.call(this, options);
        } else {
            options.callback({ results: [ALL_OPTION] });
        }
    }
});

You can't use the minimumInputLength option because it will prevent the query function from getting called. Instead, the code above uses an option named _minimumInputLength inside the query function. This means, however, that you will not get the "Please enter 2 or more characters" message in the drop down. (Unless you implement it yourself somehow.)

jsfiddle


Here's a jsfiddle that implements the "Please enter 2 or more characters" message.

Sign up to request clarification or add additional context in comments.

2 Comments

great! I'm going to test this today and then mark this answer as correct if it works. It certainly looks good, thanks John!
Can you provide an example of using Select2 4.0 to do this behavior? It does not seem to work for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.