我正在使用带有 Jquery-editable 的 Select2 并遇到 Select2 的异常行为,我正在做的是使用 ejs 模板显示可编辑的信息表,并且当用户单击 CBA 时会打开一个具有最初选择结果的 select2 框,然后用户可以在其中添加或删除选项,选项来自数据库源,当用户选择一个选项时,它会在数据库中添加一个带有所选选项的空选项,数组看起来像这样
[“ABCD”、“ONAB”、“”、“BCNU”]
我在某处读到了有关 allowClear: true 并添加了一个 placeHolder 但它根本没有帮助我。由于一切都是动态完成的,我找不到添加空选项的位置。
代码如下:
Select 2 的 Ejs/HTML 代码
<tr>
<td width="40%">Select CBA(s)</td>
<td>
<a class="cbaSelectUnit" data-emptytext="Select CBA(s)" data-original-title="Select CBA(s)" data-type="select2"></a>
</td>
选择 2 的 Javascript
$("a[data-name='Cba']").editable({
showbuttons: 'false',
emptytext: 'None',
display: function(values) {
var html = [];
html.push(values);
$(this).html(html);
},
select2: {
multiple: true,
allowClear: true,
placeholder: "Select CBA(s)",
ajax: {
// url is copied from data-source via x-editable option-passing mechanism
dataType: 'json',
// pass the '?format=select2' parameter to API call for the select2-specific format
data: function(term, page) {
return {
deptId: departmentId,
format: 'select2'
};
},
// transform returned results into the format used by select2
results: function(data, page) {
return {
results: data
};
}
},
// what is shown in the list
formatResult: function(cba) {
return cba.text;
},
// what will appear in the selected tag box
formatSelection: function(cba) {
return cba.text;
},
// rendering id of the values to data.value requirement for Select 2
id: function(cba) {
return cba.value;
},
// what is shown in the selected-tags box
initSelection: function(element, callback) {
var id = $(element).val(),
result = id.replace(/^,\s*$/, ',').split(",").map(function(v) {
return {
id: v,
text: v
};
});
callback(result);
}
}
});
从数据库返回代码的格式:-
Facility.findOne({ _id: department.Facility }, function(err, facility) {
if (err) {
res.send(500, err);
} else if (!facility) {
res.send(404, 'Facility not found');
} else if (req.query.format && req.query.format === 'select2') {
var result = facility.Cba.map(function(c) {
return { value: c, text: c };
});
res.json(result);
}
});
显示自己添加的空框的图像
我编辑后数组的外观