Javascript – Jquery select2 custom javascript function when searching

ajaxjavascriptjqueryselect2

I have severall select2 in my page.
I have a specific ajax engine and can't change it for many reasons.
i would like to fill each select2 dropdown when the end-user type in the field, and use home made javascript to fill the "options" in the select2.

I've tried many different things found on the net, and can't find a working syntax for that.

For instance :

      jQuery("customer").select2({
          query: function (options) {
              alert('ok');
              // my ajax call would be here
              xajax_getCustomers(stringFilled);
          }
      });

i've tried with "ajax:" and several other things, i can't find how to trigger a javascript function when something filled.
Important : i should be able to get the string filled, in order to pass it to my ajax call

Thanks for your help

Best Answer

You have got this event:

  $(selector).on("select2-highlight", function(e) {
      console.log("highlighted val=" + e.val + " choice=" + e.choice.text);
  })

It's valid for a search event, so when select2-highlight event is fired means that user is searching for a string that you can manage with the e.val and e.choice.text values.

Unfortunatelly there's no strict search event, but you can bind the hided input text of the plugin with a on('keyup');

Something like this:

 $('input.select2-search__field').on('keyup', function() {
      alert($(this).val()); // it alerts with the string that the user is searching
 });