I am using AJAX fetched data in Select2. My code is like below.
let selectEle = cellEle.children("select").select2({
ajax: {
//more code here
},
processResults: function (data) {
var options = [];
if (data) {
$.each(data, function (index, text) {
var user_data = '<table>
<tr>
<td>Organisation</td>
<td>'+text[2][1]+'</td>
</tr>
<tr>
<td>Age</td>
<td>'+ text[2][0]+'</td>
</tr>
</table>';
options.push({ id: index, text: text[0], text1: text[1], text2: user_data });
});
}
return {
results: options,
more: false
};
},
},
templateSelection: formatState,
templateResult: resultfucntion,
});
My formatState
function is like below.
function formatState(state) {
if (!state.id) { return state.text; }
var output = $(
'<span class="tooltip" title="'+ state.text2 +'">' + state.text + '</span>'
);
return output;
};
I am fetching preselected values using AJAX and attached with Select2 like below.
$.ajax({
type: 'POST',
dataType: 'json',
url: "/wp-admin/admin-ajax.php",
data: {
element_id: element_id,
action: 'get_preselect_values',
},
}).then(function (data) {
var options = [];
if (data) {
$.each(data, function (index) {
options.push(new Option(data[index].text, data[index].id, true, true));
});
}
selectEle.append(options).trigger('change');
Everything is working fine all above.
How can I template preselected values like above ?