简体   繁体   中英

get current element in select2

I want to use multiple select2 by using a class, like I am doing in autocomplete, but I am failing to do same in select2.

here is my code:

$('.select2-autocomplete').select2({
  placeholder: "Search",
  minimumInputLength: 1,
  multiple: true,
  ajax: {
    url: "http://example.com/autocomplete-results",
    dataType: 'json',
    data: function(term, page) {
      return {
        q: term,
        type: $(this.element).data('type')
      };
    },
    results: function(data, page) {
      return {
        results: data
      };
    }
  },
});

Everything is working fine except this :

type : $(this.element).data('type') 

Here I need the select2 element data-type value, but it is always undefined any idea how I can get that?

Thanks

Edit:

<input type="hidden" data-type="products" name="products" class="select2-autocomplete">
<input type="hidden" data-type="customers" name="customers" class="select2-autocomplete">

I want to show different results from ajax that is the reason I want to send data-type via ajax

You can do it capturing the active element during the select2:open event then use it into the data function

Here my example:

(function(){
var theSelect2Element = null;
$('.select2-autocomplete').select2({
   ...
   data: function(term, page) {
      return {
        q: term,
        type: $(theSelect2Element).data('type')
      };
   },
   ...
}).on('select2:open', function(e){ 
   theSelect2Element = e.currentTarget; 
}))();

Good luck!

You can use $(this.context) and it will return the original select element as jQuery object.

data: function(term, page) {
  return {
    q: term,
    type: $(this.context).data('type')
  };
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM