【问题标题】:Select2 - avoiding duplicates tagsSelect2 - 避免重复标签
【发布时间】:2013-11-23 10:40:43
【问题描述】:

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

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

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

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

【问题讨论】:

  • 注意 3.3.0 和 3.3.1 的 select2 有一个与重复值相关的错误...
  • 谢谢。我正在使用最新的 3.4.5。
  • 我也有同样的问题。我得到重复。我初始化了选择,但之后在 ajax 调用时它会忽略已经存在的值并添加重复项。

标签: javascript jquery jquery-select2


【解决方案1】:

有同样的问题,但我想办法解决。 我正在获取文本和 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());
    }
}

希望对你有帮助。

【讨论】:

    【解决方案2】:

    第一次使用select 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");   });
    

    【讨论】:

      猜你喜欢
      • 2020-07-23
      • 2015-04-05
      • 2016-06-11
      • 2011-09-07
      • 1970-01-01
      • 2022-01-11
      • 2011-10-10
      • 2021-12-31
      • 2020-07-06
      相关资源
      最近更新 更多