I am trying to populate some preselected values to Select2. My code is like below.
(function($) {
$(document).ready(function() {
$(".volunteer").on("click", function (event) {
let element_id = event.target.id;
// Check if select is already loaded
if (!$(this).has("select").length) {
var cellEle = $(this);
// Populate select element
cellEle.html(`<select multiple="multiple"></select>`);
// Initialise select2
let selectEle = cellEle.children("select").select2({
allowClear: true,
maximumSelectionLength: 3,
ajax: {
url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
dataType: 'json',
data: function (params) {
return {
action: 'get_data',
};
},
type: "post",
processResults: function (data) {
var options = [];
if ( data ) {
$.each( data, function( index, text ) {
options.push({ id: index, text: text });
});
}
return {
results: options
};
}
}
});
selectEle.select2('open');
$.ajax({
type: "POST",
dataType: 'json',
url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
data: {
element_id: element_id,
action: 'get_preselect_values',
},
success: function (data) {
var options = [];
if (data) {
$.each( data, function( index, text ) {
options.push({ id: index, text: text });
});
}
selectEle.val(options).trigger('change'); // I am trying to attach value here. But it is not working.
}
});
selectEle.on('select2:select', function () {
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
data: {
selected_items: selectEle.val(),
element_id: element_id,
action: 'save_data'
}
});
});
selectEle.on("select2:unselecting", function () {
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
data: {
selected_items: selectEle.val(),
task_id: element_id,
action: 'save_data'
}
});
}).trigger('change');
}
});
});
})(jQuery)
I am trying to attach values but it is not working.