我在 SteveR 的答案中添加了一些功能,因为即使有结果,我也希望该值出现在下拉列表的顶部。如果我想添加的数据库中不存在所选项目,也可以添加:
$("#my_input").tokenInput(my_results_route), {
hintText: "Select labels",
noResultsText: "No results",
searchingText: "Searching...",
preventDuplicates: true,
onResult: function(item) {
if($.isEmptyObject(item)){
return [{id:'0', name: $("tester").text()}];
} else {
//add the item at the top of the dropdown
item.unshift({id:'0', name: $("tester").text()});
return item;
}
},
onAdd: function(item) {
//add the new label into the database
if(!parseInt(item.id)) {
//database insertion ajax call
console.log('Add to database');
}
}
});