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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With