Reputation: 953
I'm using Select2 to fill Dropdowns. Select2 is slow when opening its dropdown menu if the underlying select has a fair number of items. I have more than 10.000+ elements in my dropdown.
Here is my code:
$.ajax({
url: "/Companies/GetCompanies",
method: "get",
success: function (data) {
if (data != null) {
var newWorkPlaceId = $("#newWorkPlaceId");
newWorkPlaceId.empty();
newWorkPlaceId.append("<option value=''> -- Choose-- </option>");
$.each(data, function (index, item) {
newWorkPlaceId.append(
$('<option>', {
value: item.id,
text: item.text
}, '</option>'));
});
$("#newWorkPlaceId").select2({
placeholder: {
id: "",
placeholder: " -- Choose--"
},
allowClear: true
});
}
clearconsole();
}
});
Is there a way to make the Select2 widget (or another searchable dropdown) respond faster?
Note: I am using ASP.NET CORE
Upvotes: 2
Views: 12838
Reputation: 953
After long research I found that 2 symbols limitation will help me to fix this. Here is my solution
$("#newWorkPlaceId").select2({
allowClear: true,
placeholder: {
id: "",
placeholder: "Choose."
},
language: {
inputTooShort: function (args) {
return "2 or more symbol.";
},
noResults: function () {
return "Not Found.";
},
searching: function () {
return "Searching...";
}
},
minimumInputLength: 2,
ajax: {
url: 'url',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function(term) {
return {
term: term.term
};
},
processResults: function (response) {
return {
results: response
};
}
}
});
Upvotes: 2
Reputation: 6733
You have to use AJAX data and pagination like below
$('#mySelect2').select2({
ajax: {
url: 'https://api.github.com/search/repositories',
data: function (params) {
var query = {
search: params.term,
page: params.page || 1
}
// Query parameters will be ?search=[term]&page=[page]
return query;
}
}
});
Example
$('#mySelect2').select2({
ajax: {
url: function (params) {
return 'https://api.github.com/search/repositories?q='+params.term+'&page='+params.page || 1;
},
processResults: function (data) {
return {
results: $.map(data.items, function (item) {
return {
text: item.name,
id: item.id
}
})
};
}}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<select style="width:50%" id="mySelect2"></select>
Upvotes: 3