Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 328
PeraMika Avatar asked Oct 27 '25 18:10

PeraMika


2 Answers

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

like image 80
Dekel Avatar answered Oct 30 '25 09:10

Dekel


You can just rewrite the transport option, return null while validation failed, otherwise return the original function code

It works for me.

{
    data: function (params) {
        return {
            q: params.term
        };
    },
    transport: function (params, success, failure) {
        if(params.data.q.trim().length < 3) {
            return null;
        }
        //the original function code:
        var $request = $.ajax(params);

        $request.then(success);
        $request.fail(failure);

        return $request;
    },
}
like image 30
Micky Avatar answered Oct 30 '25 07:10

Micky