3

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

Vitaliy Terziev
  • 6,429
  • 3
  • 17
  • 25
Micbol12
  • 53
  • 1
  • 4

1 Answers1

5

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
 });
Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
  • i've tried below code and this works, i get the string filled, BUT i don't know which select2 it refers to. any idea to know it ? `jQuery(document).on("keyup",".select2-input", function (event) { alert(jQuery(this).val()); }); ` – Micbol12 Feb 17 '16 at 11:44
  • Change `document` with your selector. If you have a select with `id="mySelect"` this converts to: `jQuery('#mySelect').on('keyup', '.inputclass', .... );` – Marcos Pérez Gude Feb 17 '16 at 11:54
  • doesn't work if i put the select id instead of document. – Micbol12 Feb 17 '16 at 12:21
  • not the ` – Marcos Pérez Gude Feb 17 '16 at 12:24
  • 1
    Then i probably have another problem : i do it with a classical select, but it doesn't work if i use a simple div instead. If i do : `jQuery("#customer").select2();` i receive an error "Uncaught query function not defined for Select2 customer" (jquery 3.5.2) Then i'm stuck... – Micbol12 Feb 17 '16 at 13:49
  • Yes, it happens when you try to initialise a select that there was initialised before, because it wraps the new div with the same properties as the native ` – Marcos Pérez Gude Feb 17 '16 at 14:01
  • This answer contains code from both Select2 3.x and Select2 4.x, that's why it's not working. – Kevin Brown-Silva Feb 18 '16 at 12:18