Skip to content

Instantly share code, notes, and snippets.

@thinhbuzz
Created October 8, 2021 11:00
Show Gist options
  • Save thinhbuzz/c98fac198d83927e2c495cf778a669d0 to your computer and use it in GitHub Desktop.
Save thinhbuzz/c98fac198d83927e2c495cf778a669d0 to your computer and use it in GitHub Desktop.
select2 pagination without ajax
var items = Array.from(Array(500))
.fill(0)
.map(function (i, index) {
return {
id: index,
text: "item - " + index,
};
});
$(document).ready(function () {
$.fn.select2.amd.require(
[
"select2/data/array",
"select2/results",
"select2/dropdown/infiniteScroll",
"select2/utils",
],
function (ArrayData, ResultsList, InfiniteScroll, Utils) {
function CustomData($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
}
Utils.Extend(CustomData, ArrayData);
var ResultsAdapter = Utils.Decorate(ResultsList, InfiniteScroll);
CustomData.prototype.query = function (params, callback) {
console.log(params, this.options);
var pageSize = 20;
var page = params.page || 1;
var results = [];
var data = this.options.options.data || [];
var term = (params.term || "").trim().toUpperCase();
if (term) {
results = data.filter(function (item) {
return item.text.toUpperCase().indexOf(term) >= 0;
});
} else {
results = data;
}
callback({
results: results.slice((page - 1) * pageSize, page * pageSize),
pagination: {
more: results.length >= page * pageSize,
},
});
};
$('[name="selectbox"]').select2({
data: items,
dataAdapter: CustomData,
resultsAdapter: ResultsAdapter,
});
}
);
});
@thinhbuzz
Copy link
Author

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