Default selected value doesn`t show label

I use this piece of code to set the default selected option for my Select2, It also gets data via ajax:

var $element = $('#posttagform-tags').select2();
let data = JSON.parse($element.attr("data-selectedTags"));
for (var d = 0; d < data.length; d++) {
    var item = data[d];
    var option = new Option(item.text, item.id, true, true);
    $element.append(option).trigger('change')
}

this code generates this HTML:

'<ul class="select2-selection__rendered"><span class="select2-selection__clear">×</span>
<li class="select2-selection__choice" title="ddd"><span class="select2-selection__choice__remove" role="presentation">×</span></li>
<li class="select2-selection__choice" title="pet"><span class="select2-selection__choice__remove" role="presentation">×</span></li>
<input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="none" spellcheck="false" role="textbox" aria-autocomplete="list" placeholder="" style="width: 0.75em;">
<li class="select2-search select2-search--inline"></li>
'

There isn`t any label inside each li tag, but li tag has title with the value that should be as the label of the option.

I cannot reproduce the behavior you described, but I don’t have an AJAX data source I can use either. Could you show the HTML and JavaScript code you’re using to create the <select> element and load the data? It appears you’re not using Select2’s AJAX feature (although that shouldn’t matter). I suspect it really doesn’t matter how you’re loading the data, but have you tried hard-coding the data in your HTML <select>, and seeing if you experience the same issue?

Alternatively, could you put your code on jsfiddle or codepen.io? It’s possible that the data you’re using to create the Option elements has something to do with this, but since I can’t see the data, I can’t confirm or refute that.

@John30013 thanks for replay. I found out where is a problem. I have changed the default template result callback from

    function (item) {return item.text }

on

    function (item) {return item.name; }

And andpoint for ajax request had given me json in next view : [{id:2,name:‘News’}, {id:3: name:‘Trump’}] and all worked fine when I search tags, but when I wanted set default data it didn`t.

So I have turned back the default callback result and all begun worked fine.

Hi, Yurii–

I’m glad you figured out the issue. For what it’s worth, you should be able to map your AJAX return data to the format that Select2 expects; see https://select2.org/data-sources/formats#transforming-data-into-the-required-format.