Skip to content

Instantly share code, notes, and snippets.

@techniq
Created January 23, 2013 16:24
Show Gist options
  • Save techniq/4609063 to your computer and use it in GitHub Desktop.
Save techniq/4609063 to your computer and use it in GitHub Desktop.
Select2 ajax example with custom query call to append data to the request. Note: Providing ajax settings is not needed (and not used) when query is provided. Left here as a full example.
$("[data-provide='select2']").each(function () {
var $element = $(this);
$element.select2({
placeholder: $element.data("placeholder"),
minimumInputLength: 0,
allowClear: true,
initSelection: function (element, callback) {
callback({
id: $(element).val(),
text: $(element).data('selected-text')
});
},
query: function (query) {
var url = $element.data("url");
var contextData = {};
var contexts = $element.data("context").split(",");
_.map(contexts, function (c) {
var name = c.trim();
var value = $("[name='" + name + "']").val();
if (value) {
contextData[name] = value;
}
});
var data = {
query: query.term,
page: query.page,
pageLimit: 25
};
$.extend(data, contextData);
$.post(url, data, function (results) {
query.callback(results);
});
},
ajax: {
url: $element.data("url"),
type: "POST",
quietMillis: 100,
data: function (term, page) {
return {
query: term,
page: page,
pageLimit: 25
};
},
results: function (data, page) {
return data;
}
}
});
});
@renierdbruyn
Copy link

Can you please show the html that goes with this? As it would increase, at least, my understanding of your gist

@ragingprodigy
Copy link

Nice guide. Needed a way to use this in an AngularJs directive. Rather than use jQuery though, I used the $http service.

https://gist.github.com/ragingprodigy/671142d37a7c588383ba

@romeshniriella
Copy link

I was looking for something like this query() function all over. thanks a lot.
created a gist with my scenario. Gist: Select2 Grouped Static Data With AJAX Fallback

@gaojing007
Copy link

how to delay when use query function?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment