Reputation: 155
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
Upvotes: 2
Views: 5676
Reputation: 15
You can use $('.select2-container--open').prev('select.select2-autocomplete') and it will return the original select element as jQuery object.
data: function(term, page) {
return {
q: term,
type: $('.select2-container--open').prev('select.select2-autocomplete').data('type')
};
}
Upvotes: 0
Reputation: 5313
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')
};
},
Upvotes: 2
Reputation: 116
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!
Upvotes: 7