Search code examples
javascriptjquery-select2-4

Change remote url based on search query


I have a select2 field which is retrieving data from a remote api. I can get that working. What I'm trying to do is change the remote url based on what the user has typed. If the first two letters typed are for example "AA" then search using a url and when the first two characters are "88" then search using another url.

This is my code so far:

this.selector.select2({
     minimumInputLength: 2,
     ajax: {
         url: function(param){return 'http://localhost:3000/suggestions?&'},
         dataType: 'json' ,
         data: function (params) {


      var query = {
       search: params.term,
      }
      return query;
    },
          processResults: function(data) {
            var results = []; 
            $.each(data, function (index, search) {
                 results.push({
                     id: search.id,
                     text: search.val
                 });
             });

             return {
              "results":results
             };                            
         },

     },

     width: 'resolve',
  }); 

I've looked but can't find an event which is fired when typing(searching).


Solution

  • According to docs the params argument passed to url callback is the same as in data callback. So you can rewrite your code as:

    this.selector.select2({
      minimumInputLength: 2,
      ajax: {
        url: function (params) {
          var firstTwoLetters = params.term.slice(0, 2);
          if (firstTwoLetters == '88') {
            return 'some url';
          } else if (firstTwoLetters == 'AA') {
            return 'another url'
          } else {
            return 'http://localhost:3000/suggestions?&'
          }
        },
        dataType: 'json',
        data: function (params) {
          var query = {
            search: params.term,
          }
          return query;
        },
        processResults: function (data) {
          var results = [];
          $.each(data, function (index, search) {
            results.push({
              id: search.id,
              text: search.val
            });
          });
    
          return {
            "results": results
          };
        },
    
      },
    
      width: 'resolve',
    });