I'm currently utilizing the select2 plugin (v.4.0) and have a specific goal in mind:
$("#search-input-chains").select2({
placeholder: "Unit",
theme: "bootstrap4",
allowClear: true,
initSelection: function (element, callback) {
callback({id: 1, text: 'Text'});
},
ajax: {
url: function () {
return getURLForFilial();
},
dataType: 'json',
delay: 250,
processResults: function (response) {
console.log(response);
return {
results: response
};
},
cache: false
}
});
function getURLForFilial() {
return '/user/rest/data/entry/units/branches?type=1';
}
I am aiming to determine whether my control has successfully retrieved data from the database or not. If there is no data present, I would like to deactivate the select list. I have discovered one way to check the data amount as follows:
$("#search-input-chains").data().select2.results.$results[0].childNodes.length
(Is there a more efficient method to achieve this?) However, the above code returns a count of 0 until I manually activate (click) on the select2 box and trigger an AJAX request to fetch the data. I've researched ways to pre-load AJAX calls but have not been successful. I attempted triggering an event on select2 using the following code:
$("#search-input-chains").val().trigger('change');
Can someone provide guidance on how I can load data onto my select2 control during page load to determine whether I should disable the select option?