Select2 - 避免重复的标签

3

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

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

此外,提交表单时需要使用标签的text而不是来自下拉列表的id

console.log

完整分辨率

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)
    }
});

Select2的3.3.0和3.3.1版本存在与重复值相关的错误。 - mccannf
谢谢。我正在使用最新的3.4.5版本。 - kros
我有同样的问题。我得到了重复项。我初始化选择,但随后在ajax调用中忽略已经存在的值并添加重复项。 - Yaron
2个回答

0

首先使用选择2

然后执行以下操作:

$("select").change(function() {     var tr = $(this).closest("tr");
    tr.find("select option").attr("disabled",""); //enable everything

 //collect the values from selected;
 var  arr = $.map
 (
    tr.find("select option:selected"), function(n)
     {
          return n.value;
      }
  );

//disable elements
tr.find("select option").filter(function()
{

    return $.inArray($(this).val(),arr)>-1; //if value is in the array of selected values
 }).attr("disabled","disabled");   });

0

我也遇到了同样的问题,但是我找到了解决方法。我获取文本和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());
    }
}

希望能有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接