选择2:使用ajax创建标签



我正在使用select2库。

我的 select2 元素可以通过 ajax 在数据库中搜索每个标签,并且工作正常。

我的问题是,我希望用户也能够创建一个新标签。查看他们的文档,我应该使用createTag选项;但是,一旦我单击元素并在每次按键时都会触发。

任何人都可以就我如何实现目标提供任何指导吗?

这是我到目前为止的代码

I am using ajax top search for tags but I would also like to create new tags to the database. I have tried doing this via createTag but this seems to be firing as soon as I click in the HTML element and on each key press.
Here is my code:
$('.tags').select2({
tags: true,
placeholder: "These tags will apply to all lines",
tokenSeparators: [','],
ajax: {
url: '/api/tags/find',
dataType: 'json',
data: function (params) {
return {
q: $.trim(params.term)
};
},
processResults: function (data) {
return {
results: data
}
},
cache: true,
},
createTag: function(params) {
alert('tag created') // This is were I would put my ajax POST. 
}
});

再次阅读文档后,我可以看到我应该一直在使用事件 https://select2.org/programmatic-control/events

我使用createTag选项将newTag: true分配给新创建的标签,并使用select2:selected事件检查是否选择了新标签,如果是,则向服务器发送 ajax 请求以创建该标签。


$('.tags').select2({
tags: true,
placeholder: "These tags will apply to all lines",
minimumInputLength: 3,
tokenSeparators: [','],
ajax: {
url: '/api/tags/find',
dataType: 'json',
data: function (params) {
return {
q: $.trim(params.term)
};
},
processResults: function (data) {
return {
results: data
}
},
// cache: true,
},
createTag: function(params) {
let term = $.trim(params.term);
if (term.length < 3)
{
return null
}
return {
id: term,
text: term,
newTag: true,
}
},
});
$('.tags').on('select2:select', function (e) {
let tag = e.params.data;
if (tag.newTag === true)
{
axios.post('/api/newtag', {
name: tag.text,
type: 'default',
})
}
});

最新更新