【问题标题】:Tagging with AJAX in select2在 select2 中使用 AJAX 进行标记
【发布时间】:2012-12-23 04:17:05
【问题描述】:

我正在使用select2 进行标记

我对 select2 有这些要求:

  1. 我需要使用 select2 ajax 搜索一些标签
  2. 我还需要在 select2 中使用“标签”,它允许不在列表中的值(Ajax 结果)。

这两个场景都是独立工作的。但是连接在一起的 aJax 值只会被填充。如果我们键入列表中没有的任何其他值,那么它会显示“未找到匹配项”

我的场景如果用户键入任何不在列表中的新值,允许他们组成自己的标签。

有什么办法可以做到这一点?

【问题讨论】:

    标签: javascript jquery jquery-select2


    【解决方案1】:

    Select2 具有“createSearchChoice”功能:

    从用户的搜索词中创建一个新的可选选项。允许 无法通过查询功能创建选择。有用的时候 用户可以即时创建选择,例如“标记”用例。

    您可以通过以下方式实现您想要的:

    createSearchChoice:function(term, data) {
      if ($(data).filter(function() {
        return this.text.localeCompare(term)===0;
      }).length===0) {
        return {id:term, text:term};
      }
    },
    multiple: true
    

    这是一个更完整的答案,它将 JSON 结果返回到 ajax 搜索,并允许从该术语创建标签,如果该术语没有返回结果:

    $(".select2").select2({
      tags: true,
      tokenSeparators: [",", " "],
      createSearchChoice: function(term, data) {
        if ($(data).filter(function() {
          return this.text.localeCompare(term) === 0;
        }).length === 0) {
          return {
            id: term,
            text: term
          };
        }
      },
      multiple: true,
      ajax: {
        url: '/path/to/results.json',
        dataType: "json",
        data: function(term, page) {
          return {
            q: term
          };
        },
        results: function(data, page) {
          return {
            results: data
          };
        }
      }
    });
    

    【讨论】:

    • 如果使用这个 sn-p 会遇到困难:$(data).filter 函数是匹配发生的地方,this.text 只是返回的 text 键的值JSON。例如,如果您要返回联系人列表,则需要检查 this.name。此外,如果您在远程文件 (/path/to/results.json) 中进行某种术语匹配,您只需确保返回的项目具有您需要的属性,并且在之后没有未定义或格式错误从远程文件返回。 (呼,很好的答案。谢谢克里斯!)
    • 你能看看这个问题吗? stackoverflow.com/questions/35231584/…
    【解决方案2】:

    选择 v4

    http://jsfiddle.net/8qL47c1x/2/

    HTML:

    <select multiple="multiple" class="form-control" id="tags" style="width: 400px;">
        <option value="tag1">tag1</option>
        <option value="tag2">tag2</option>
    </select>
    

    JavaScript:

    $('#tags').select2({
        tags: true,
        tokenSeparators: [','],
        ajax: {
            url: 'https://api.myjson.com/bins/444cr',
            dataType: 'json',
            processResults: function(data) {
              return {
                results: data
              }
            }
        },
    
        // Some nice improvements:
    
        // max tags is 3
        maximumSelectionLength: 3,
    
        // add "(new tag)" for new tags
        createTag: function (params) {
          var term = $.trim(params.term);
    
          if (term === '') {
            return null;
          }
    
          return {
            id: term,
            text: term + ' (new tag)'
          };
        },
    });
    

    选择 v3.5.2

    一些改进的例子:

    http://jsfiddle.net/X6V2s/66/

    html:

    <input type="hidden" id="tags" value="tag1,tag2" style="width: 400px;">
    

    js:

    $('#tags').select2({
        tags: true,
        tokenSeparators: [','],
        createSearchChoice: function (term) {
            return {
                id: $.trim(term),
                text: $.trim(term) + ' (new tag)'
            };
        },
        ajax: {
            url: 'https://api.myjson.com/bins/444cr',
            dataType: 'json',
            data: function(term, page) {
                return {
                    q: term
                };
            },
            results: function(data, page) {
                return {
                    results: data
                };
            }
        },
    
        // Take default tags from the input value
        initSelection: function (element, callback) {
            var data = [];
    
            function splitVal(string, separator) {
                var val, i, l;
                if (string === null || string.length < 1) return [];
                val = string.split(separator);
                for (i = 0, l = val.length; i < l; i = i + 1) val[i] = $.trim(val[i]);
                return val;
            }
    
            $(splitVal(element.val(), ",")).each(function () {
                data.push({
                    id: this,
                    text: this
                });
            });
    
            callback(data);
        },
    
        // Some nice improvements:
    
        // max tags is 3
        maximumSelectionSize: 3,
    
        // override message for max tags
        formatSelectionTooBig: function (limit) {
            return "Max tags is only " + limit;
        }
    });
    

    JSON:

    [
      {
        "id": "tag1",
        "text": "tag1"
      },
      {
        "id": "tag2",
        "text": "tag2"
      },
      {
        "id": "tag3",
        "text": "tag3"
      },
      {
        "id": "tag4",
        "text": "tag4"
      }
    ]
    

    2015 年 1 月 22 日更新:

    修复 jsfiddle:http://jsfiddle.net/X6V2s/66/

    2015 年 9 月 9 日更新:

    使用 Select2 v4.0.0+ 变得更容易。

    选择 v4.0.0

    https://jsfiddle.net/59Lbxvyc/

    HTML:

    <select class="tags-select" multiple="multiple" style="width: 300px;">
      <option value="tag1" selected="selected">tag1</option>
      <option value="tag2" selected="selected">tag2</option>
    </select>
    

    JS:

    $(".tags-select").select2({
      // enable tagging
      tags: true,
    
      // loading remote data
      // see https://select2.github.io/options.html#ajax
      ajax: {
        url: "https://api.myjson.com/bins/444cr",
        processResults: function (data, page) {
          return {
            results: data
          };
        }
      }
    });
    

    【讨论】:

    • 非常好的演示 :) @faost
    • 谢谢你——救命!和时间:P
    • @faost 你能看看这个。如果可能的话stackoverflow.com/questions/35216302/…
    • @faost:您的演示自动完成中的 select2 v4.0.0 不起作用,也不能过滤/查找单词
    • @ಠ_ಠ select2 发送搜索词作为查询参数,在我的示例中,请求如下所示:GET https://api.myjson.com/bins/444cr?q=TEST。但是api.myjson.com/bins/444cr 是一个静态 URL,它不能处理查询参数。在实际应用中,您的后端将使用此查询参数“q”来过滤结果。
    【解决方案3】:
    createSearchChoice : function (term) { return {id: term, text: term}; }
    

    只需添加此选项项

    【讨论】:

    • 你不应该这样做,因为如果你有现有的标签,用户将有两个相同标签的选择,例如'test'(来自数据库)和'test' - 新创建的。您应该检查术语是否已经在数据中。
    【解决方案4】:

    您可以通过让您的 ajax 函数也返回搜索词作为结果列表中的第一个结果来完成这项工作。然后用户可以选择该结果作为标签。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 2018-02-13
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多