CreateSearchChoice 应该是您要查找的内容
这是我不久前问过的一个类似的 SO select2 createSearchChoice id from post
createSearchChoice: function (term, data) {
if ($(data).filter(function () {
return this.text.localeCompare(term) === 0;
}).length === 0) {
// if not found in current list
// return {id:term, text:term}
return {
id: term,
text: $.trim(term) + ' (new tag)'
};
},
请注意,我将 id 设置为新的文本术语,您可以将其设置为像 -1/term 这样的连接值,然后稍后将其解析出来,但术语必须包含在此解决方案的 ID 中
然后在更改事件中,我确定 id 是否为数字(已经存在)。如果它不是数字(在 createsearchchoice 中添加),我将完成发布到标签数据库的过程
.on("change", function(e) {
if (e.added) { //is it added from select2
if (isNumeric(e.added.id)){ //did it already exist or createsearchchoice
add(e.added.id); //it already existed, just add it to the tag list
} else { //id was created on the fly, post to the database and return a tag id
$.post('handlers/tags.ashx', {
operation:"select2createtag",
//because its not numeric, we know id = new tag text
text: $.trim(e.added.id)} ,
function(data){
//set the added id to the id you just returned from sql
e.added.id = data.id;
//...do something else, like then add the new tag to the item
});
};
};
如果您不想发布到 ajax,请让您的服务器端评估您的输入项,以及任何 id 的非数字标签,请遵循上述相同的想法
I updated your Plunker here