Paperback Writer Paperback Writer - 1 year ago 882
jQuery Question

How to enable infinite scrolling in select2 4.0 without ajax

I am using

with custom data adapter. All of the data provided to
is generated locally in web page (so no need to use ajax). As
method can generate a lot of results (about 5k) opening select box is quite slow.

As a remedy, I wanted to use infinite scroll. Documentation for custom data adapter says that
method should receive
parameter together with

@param The specific page that should be loaded. This is
typically provided when working with remote data sets, which rely
on pagination to determine what objects should be displayed.

But it does not: only
is present. I tried to return
more: true
more: 1000
, but this didn't help. I guess this is because, by default, infinite scroll is enabled iff ajax is enabled.

I am guessing that enabling infinite scroll will involve using
, but I am not sure what to do exactly. I tried this code:

["select2/utils", "select2/dropdown/infiniteScroll"],
(Utils, InfiniteScroll) =>"select2").options.options.resultsAdapter =
Utils.Decorate("select2").options.options.resultsAdapter, InfiniteScroll)

This is coffee script, but I hope that it is readable for everyone.
element containing select box - I earlier did
input.select2( //options )

My question is basically, how do I enable infinite scroll without

Answer Source

Select2 will only enable infinite scroll, if ajax is enabled. Fortunately we can enable it and still use our own adapter. So putting empty object into ajax option will do the trick.

  ajax: {},
  dataAdapter: CustomData

Next, define your own data adapter. Inside it, inn query push pagination info into callback.

    CustomData.prototype.query = function (params, callback) {
        if (!("page" in params)) {
   = 1;
        var data = {};
        # you probably want to do some filtering, basing on params.term
        data.results = items.slice(( - 1) * pageSize, * pageSize);
        data.pagination = {};
        data.pagination.more = * pageSize < items.length;

Here is a full fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download