简体   繁体   English

在select2中使用AJAX标记

[英]Tagging with AJAX in select2

I am doing tagging with select2 我正在使用select2进行标记

I have these requirements with select2: 我对select2有这些要求:

  1. I need to search some tags using select2 ajax 我需要使用select2 ajax搜索一些标签
  2. Also I need to use "tags" in select2 which Allows values that are not in the list(Ajax result). 另外,我还需要在select2中使用“标签”,以允许列表(Ajax结果)中未包含的值。

Both the scenarios work independently. 两种方案均独立工作。 But joined together aJax values are only populated. 但是仅将aJax值连接在一起。 If we type any other values not in the list then it says "no matches found" 如果我们键入列表中未包含的其他任何值,则显示“找不到匹配项”

My scenario If user type any new value which is not in the list, allow them to make up their own tag. 我的方案如果用户键入列表中未包含的任何新值,则允许他们组成自己的标签。

Any way to make this work? 有什么办法可以使这项工作吗?

Select2 has the function "createSearchChoice": Select2具有功能“ createSearchChoice”:

Creates a new selectable choice from user's search term. 根据用户的搜索词创建一个新的可选选项。 Allows creation of choices not available via the query function. 允许创建查询功能不可用的选项。 Useful when the user can create choices on the fly, eg for the 'tagging' usecase. 当用户可以动态创建选择时很有用,例如用于“标记”用例。

You could achieve what you want by using: 您可以使用以下方法实现所需的功能:

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

Here's a more complete answer that returns a JSON result to an ajax search, and allows tags to be created from the term, if the term returned no results: 这是一个更完整的答案,它将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
      };
    }
  }
});

Select v4 选择v4

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

HTML: HTML:

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

JavaScript: 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)'
      };
    },
});

Select v3.5.2 选择v3.5.2

Example with some improvements: 具有一些改进的示例:

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

html: 的HTML:

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

js: 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: JSON:

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

UPDATED 2015-01-22: 2015年1月22日更新:

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

UPDATED 2015-09-09: 2015-09-09更新:

With Select2 v4.0.0+ it became easier. 使用Select2 v4.0.0 +,它变得更加容易。

Select v4.0.0 选择v4.0.0

https://jsfiddle.net/59Lbxvyc/ https://jsfiddle.net/59Lbxvyc/

HTML: 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: 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
      };
    }
  }
});
createSearchChoice : function (term) { return {id: term, text: term}; }

只需添加此选项

You can make this work, by having your ajax function also return the search term, as the first result in the result list. 您可以通过使ajax函数也返回搜索项作为结果列表中的第一个结果来完成此工作。 The user can then select that result as a tag. 然后,用户可以选择该结果作为标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM