Select2 Predefined Selected option shows blank on rendered

When I predefined a selected value from ajax or even hardcoded preselected option it just shows blank

Image Link

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?

I think the problem is that the <option> element you’re appending to the <select> does not have its selected attribute set. Note that the Select2 documentation (which it seems you’re not precisely following), appends a new Option(data.name, data.id, true, true). Note especially those last two true parameters. These set the defaultSelected and selected properties of the new Option object. If you want to do the same by appending an HTML <option> element instead, then you need to set the selected attribute in the HTML string.

(Note: I would suggest that you use the same approach that the Select2 documentation does, and create a new Option object, rather than building one via an HTML string. I see that you want to set the title attribute of the <option>, but you can do that on an Option object too:

// create the option and append to Select2.
const defaultOption = new Option(data.name, data.id, true, true);
defaultOption.setAttribute("title", data.title);
material.append(defaultOption).trigger('change.select2');
// manually trigger the `select2:select` event
...
1 Like