Search code examples
jqueryajaxtrimjquery-select2jquery-select2-4

Select2: Trim entered text and if empty - prevent sending Ajax requests


I am using Select2 with Ajax to load remote data (suggestions).

Everything works fine, but there is one problem: when a user enters only spaces (by pressing the spacebar) - Ajax request is being sent.

How can I prevent this? Also, I would like to trim terms before being sent.

$(".js-data-example-ajax").select2({
  placeholder: "Select... ",
  minimumInputLength: 3,
  ajax: {
    url: "/my-site/tags",
    dataType: 'json',
    data: function (params) {
        return {
            q: params.term
        };
    },
    processResults: function (data) {
        return {
            results: data
        };
    },
    cache: true
}

EDIT:

I forgot to mention that I have already tried something like this:

        data: function (params) {
            if (params.term.trim().length  < 2) {
                return;
            }
            return {
                q: $.trim(params.term)
            };
        },

and the GET (Ajax) request is still sent.


Solution

  • You can use the data function to check the length of the search term (after trim), and return if the length < 3:

    data: function (params) {
      if (params.term.trim().length  < 3) {
        throw false;
      }
      return {
        q: params.term.trim()
      };
    },
    

    I was trying to get the value of minimumInputLength from inside the data function but couldn't, so you should use have this number written twice.

    update

    The only way I was able to stop the request was to throw exception inside the the data function. I know it's probably not a good option, but it works.

    And I also found an open ticket regarding this issue: https://github.com/select2/select2/issues/1637 So I guess there is no such option (yet).