我正在使用select2,正常工作正常,但默认选择不起作用,
我正在使用select2 4.0.3 js
我正在使用initSelection,但它的显示就像这个截图,
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,
});
你可以帮我解决这个问题吗?
谢谢
您必须触发选定的值
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');
我希望这段代码能够运作。
经过多次测试,对于4.0.3版本,这个技巧奏效了
initSelection: function (element, callback)
{
var id = $(element).val();
if (id !== "" && id !== 0)
{
$.ajax(url,
{
data: {q: id},
dataType: "json"
}).done(function (data)
{
$.each(data, function (i, value)
{
input.append('<option value='+value[0].id+' selected>'+value[0].text+'</option>');
callback({id: value[0].id,text: value[0].text});
});
;
});
}
}
这适合我.. :)
initSelection: function (element, callback)
{
var id = $(element).val();
if (id !== "" && id !== 0)
{
$.ajax("/visits/exam/findings/selected?visit_id=" + $('#visit_id').val(),
{
data: {q: id},
dataType: "json"
}).done(function (data)
{
$.each(data, function (i, value)
{
$("#basic_exam_findings").append('<option value='+value['id']+' selected>'+value['text']+'</option>');
callback({id: value['id'],text: value['text']});
});
;
});
}
}