I am using select2, everithing working fine but default selection not work,
I am using select2 4.0.3 js
I am using initSelection, but its display like this screenshot,
var data = <?php echo $cat_json; ?>;
function templateResult(node) {
var $result = $('<span style="padding-left:' + (20 * node.level) + 'px;">' + node.text + '</span>');
return $result;
};
function formatSelection(node) {
return node.sel_text;
};
$("#mySelect").select2({
initSelection: function (element, callback) {
var file_id = 29;
$.ajax({
url: "/admin/folders/get_selected_cat/" + file_id,
dataType: "json",
}).done(function (data) {
console.log(data); //Object {id: "1", text: "Product"}
callback(data.text);
});
},
placeholder: 'Select an option',
width: "600px",
tags: true,
data: data,
templateSelection: formatSelection,
templateResult: templateResult,
});
can you please help me to fix this?
thanks
You have to trigger selected value
var selected = [{id: "20"}];
var data = <?php echo $cat_json; ?>;
function templateResult(node) {
var $result = $('<span style="padding-left:' + (20 * node.level) + 'px;">' + node.text + '</span>');
return $result;
}
;
function formatSelection(node) {
return node.sel_text;
}
;
$("#mySelect").select2({
placeholder: 'Select an option',
width: "600px",
tags: true,
data: data,
templateSelection: formatSelection,
templateResult: templateResult,
});
$('#mySelect').val(selected).trigger('change');
I hope this code will work.