我无法使用select2版本4.0开发一个选项,在写完所需标签名称的几个字母(2,3个字母)后,通过ajax调用建议存储在数据库中的项目。
由于以前版本的版本initSelection
方法的更改不再存在。它产生错误"No select2/compat/initSelection".
以下是我以前版本使用的代码:
$('.addTags').select2({
placeholder: "Problem Tags",
allowClear: true,
minimumInputLength: 2,
tags: true,
createSearchChoice: function (term, data) {
if ($(data).filter(function () {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
id: term,
text: term
};
}
},
initSelection: function (element, callback) {
var tags = element.val().split(",");
var data = [];
for (var i = 0; i < tags.length; i++) {
data.push({ id: tags[i], text: tags[i] });
}
callback(data);
},
multiple: true,
ajax: {
type: 'GET',
url: "/Problem/GetTags",
dataType: 'json',
data: function (term, page) {
return {
term: term,
page_limit: 15
};
},
results: function (data, page) {
return { results: data.tags };
}
}
});
答案 0 :(得分:1)
使用Select2 4.0.0版本,您必须将createSearchChoice
更改为createTag
:
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
return {
id: term,
text: term,
newTag: true // add additional parameters
}
}
然后通常不需要initSelection
(请参阅https://select2.org/upgrading/migrating-from-35#removed-the-requirement-of-initselection)。
在ajax选项中将results
处理程序更改为processResults
:
processResults: function (data, page) {
return { results: data.tags };
},
这是一个jsfiddle,例如:https://jsfiddle.net/beaver71/bhodkpav/