Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 816
Mani Avatar asked Apr 23 '26 07:04

Mani


2 Answers

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!

like image 197
Diego La Monica Avatar answered Apr 24 '26 21:04

Diego La Monica


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')
  };
},
like image 44
Donny Kurnia Avatar answered Apr 24 '26 21:04

Donny Kurnia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!