How to set value in select2 while pagination is implemented

513 Views Asked by At

I have implemented pagination in select2 but after that I am unable to set value in select2.

My html code

<input id="test" style="width:100%;" placeholder="type text, scroll for more results" />

JS code

$('#test').val([2,10]).trigger('change');
$('#testbtn').click(function () {
alert($('#test').val());
});



function shuffle(str) {
  return str
    .split('')
    .sort(function() {
      return 0.5 - Math.random();
    })
    .join('');
}

function mockData() {
  return _.map(_.range(1, 1000), function(i) {
    return {
      id: i,
      text: shuffle('str ing to shuffle') + ' ' + i,
    };
  });
}
(function() {
  // init select 2
  $('#test').select2({
    data: mockData(),
    placeholder: 'search',
    multiple: true,
    // query with pagination
    query: function(q) {
      var pageSize,
        results,
        that = this;
      pageSize = 20; // or whatever pagesize
      results = [];
      if (q.term && q.term !== '') {
        results = _.filter(that.data, function(e) {
          return e.text.toUpperCase().indexOf(q.term.toUpperCase()) >= 0;
        });
      } else if (q.term === '') {
        results = that.data;
      }
      q.callback({
        results: results.slice((q.page - 1) * pageSize, q.page * pageSize),
        more: results.length >= q.page * pageSize,
      });
    },
  });
})();

Please find JSFiddle link for working example.

Note: When I comment query part in select2 binding its working fine.

0

There are 0 best solutions below