Andrew
Andrew

Reputation: 20091

Select2 how to wait for typing before sending ajax request

Really liking this Select2 html/JS control: https://select2.org/data-sources/ajax

When a user clicks on the select2 textbox and it receives focus, the ajax request immediately gets sent to return some default values.

Is there a setting or way to make select2 wait until at least 1, 2 or 3 letters has been typed before sending the request?

$('#search').select2({
    ajax: {
        type: 'POST',
        url: url,
        dataType: 'json',
        data: function (params) {
            return {
                search: params.term
            };
        },
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function (response) {
            return response
        }
    },
    placeholder: ''
});

Upvotes: 2

Views: 1939

Answers (1)

Andrew
Andrew

Reputation: 20091

Ok figured it out the property is minimumInputLength. See the Additional examples section of the docs.

So you could do

minimumInputLength: 3

Note you might want to do this to modify or hide the default message "Please enter 1 or more characters":

language: {
    'inputTooShort': function () {
        return '';
    }
},

Upvotes: 3

Related Questions