gpt4 book ai didi

javascript - Select2 - 避免重复标签

转载 作者:行者123 更新时间:2023-11-30 06:27:35 29 4
gpt4 key购买 nike

如何避免 Select2 输入中的重复标签?

当我在键盘上键入标签名称时,字符串被添加到输入字段,但是当我从下拉列表(来自数据库的结果)中选择标签时,id 被添加到输入(查看屏幕截图上的 console.log)。所以我可以从列表中选择标签并从键盘添加相同的标签。

此外,我在提交表单时需要标签的text,而不是下拉列表中的id

console.log

Full resolution

HTML:

<input type="hidden" id="categories" name="categories" style="width:100%" value="${categories}">

JS:

$("#categories").select2({
tags: true,
tokenSeparators: [","],
placeholder: "Dodaj",
multiple: false,
minimumInputLength: 3,
maximumInputLength: 50,
maximumSelectionSize: 20,
ajax: {
quietMillis: 150,
url: '${request.route_url("select2")}',
dataType: 'json',
data: function (term, page) {
return {
q: term,
page_limit: 10,
page: page,
};
},
results: function (data, page) {
var more = (page * 10) < data.total;
return {results: data.categories, more: more};
}
},
initSelection: function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
createSearchChoice: function (term) {
return { id: term, text: term };
},
}).change(function (e) {
if (e.added) {
console.log($("#categories").val())
console.log(e)
}
});

最佳答案

有同样的问题,但我想出了解决办法。我正在获取文本和 ID,但在服务器端,我正在根据给定的 ID 创建新对象,这些对象已被很好地阅读。

$tagsArray = explode(',', $tagNames); // it contains of my input select2 value (with ids)

foreach ($tagsArray as $tag)
{
if (is_numeric($tag))
{
$tags->append(TagQuery::create()->filterById($tag)->findOneOrCreate());
}
elseif (!empty($tag))
{
$tags->append(TagQuery::create()->filterByName($tag)->findOneOrCreate());
}
}

希望对您有所帮助。

关于javascript - Select2 - 避免重复标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20161301/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com