When I predefined a selected value from ajax or even hardcoded preselected option it just shows blank
selection___rendered is empty. I already use the latest stable but still, this bug for me exists.
Is this maybe I have multiple select2 instances, but I remove the first one but the bug still exists.
Or maybe is this from the loop
for(let index = 1; index <= $('#counter").val(); index++) {
setTimeout(()=>{
init(index, true);
},1000)
}
I change it to be hardcoded yet still the selected option doesn’t show.
var init = function(theId, onLoad = false){
const id = theId - 1;
const rootUrl = window.location.origin;
$(`#material_id-${id}`).select2({
ajax: {
url: `${rootUrl}/web-api/materials`,
dataType: 'json',
delay: 500,
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.data,
pagination: {
more: (params.page * 10) < data.total
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: formatResult,
templateSelection: formatResultSelection
});
switch(onLoad){
case true:
//Set the selected material by if exist
let materialId = $(`#material_id-exist-${id}`).val();
if(materialId !== '' || materialId !== null || materialId !== undefined){
// Fetch the preselected item, and add to the control
var material = $(`#material_id-${id}`);
$.ajax({
type: 'GET',
url: `${rootUrl}/web-api/materials/${materialId}`,
}).then(function (data) {
// create the option and append to Select2
var option = '<option value="'+data.id+'" title="'+data.title+'">'+data.name+'</option>';
material.append(option).trigger('change.select2');
// manually trigger the `select2:select` event
material.trigger({
type: 'select2:select',
params: {
data: data.name
}
});
});
}
default:
return;
}
}
Any idea?