I’m a student python/django developer whom is new to select2 4 rc and javascript. I’ve managed to get select2 working properly. However, I have a large list of data that select2 bogs down on. I’ve attempted to use the minimumInputLength, which works fine but the application still bogs down because the amount of data being loaded. The javascript I’m using is below. How can I make initial data load of the template not search data until the minimumInputLength is met?
$(document).ready(function () {
$('.js-example-basic-multiple').select2({
minimumInputLength: 3,
placeholder: 'Select a 3-4 User ID',
});
});
I’m rendering the select two function in my html below:
<div class="col"><h4 style="margin-top: 0"><strong>3-4 ID User Search</strong></h4><select class="js-example-basic-multiple" value = "{{ userid }}" style="width: 1110px" required>
{% for user in userid %}
<option value="{{ user }}"> {{ user }}</option>
{% endfor %}
</select>
I’ve tried the solution below that I found on stack overflow, but i believe that requires server side pagination, and using this solution my select2 never occurs and it shows the normal select box.
$(document).ready(function () {
$('.js-example-basic-multiple').select2({
minimumInputLength: 3,
allowClear: true,
placeholder: {
id: -1,
text: 'Enter the 3-4 user id.',
},
ajax: {
type: 'POST',
url: '',
contentType: 'application/json; charset=utf-8',
async: false,
dataType: 'json',
data: function (params) {
return "{'searchFilter':'" + (params.term || '') + "','searchPage':'" + (params.page || 1) + "'}";
},
processResults: function (res, params) {
var jsonData = JSON.parse(res.d);
params.page = params.page || 1;
var data = { more: (jsonData[0] != undefined ? jsonData[0].MoreStatus : false), results: [] }, i;
for (i = 0; i < jsonData.length; i++) {
data.results.push({ id: jsonData[i].ID, text: jsonData[i].Value });
}
return {
results: data.results,
pagination: { more: data.more,
}
};
}
}
});
});
There is also this example, but I can’t get it to work and the fiddle.js doesn’t seem to work either. http://jsfiddle.net/wphqwvLf/50/
$(function () {
items = []
for (var i = 0; i < 1000; i++) {
items.push({ id: i, text : "item " + i})
}
pageSize = 50
$.fn.select2.amd.require(["select2/data/array", "select2/utils"],
function (ArrayData, Utils) {
function CustomData($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
}
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
if (!("page" in params)) {
params.page = 1;
}
var data = {};
data.results = items.slice((params.page - 1) * pageSize, params.page * pageSize);
data.pagination = {};
data.pagination.more = params.page * pageSize < items.length;
callback(data);
};
$(document).ready(function () {
$("select").select2({
ajax: {},
dataAdapter: CustomData
});
});
})
});