Javascript 在 select2 中使用 AJAX 进行标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14229768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Tagging with AJAX in select2
提问by Sri
I am doing tagging with select2
我正在用select2做标记
I have these requirements with select2:
我对 select2 有这些要求:
- I need to search some tags using select2 ajax
- Also I need to use "tags" in select2 which Allows values that are not in the list(Ajax result).
- 我需要使用 select2 ajax 搜索一些标签
- 我还需要在 select2 中使用“标签”,它允许不在列表中的值(Ajax 结果)。
Both the scenarios work independently. But joined together aJax values are only populated. If we type any other values not in the list then it says "no matches found"
这两个场景独立工作。但是连接在一起的 aJax 值只会被填充。如果我们键入不在列表中的任何其他值,则它会显示“未找到匹配项”
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?
有什么办法可以使这项工作?
回答by Chris Edwards
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
};
}
}
});
回答by Alexander Fedorov
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:
一些改进的示例:
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-01-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
};
}
}
});
回答by chuck911
createSearchChoice : function (term) { return {id: term, text: term}; }
just add this option item
只需添加此选项
回答by Tor
You can make this work, by having your ajax function also return the search term, as the first result in the result list. The user can then select that result as a tag.
您可以通过让 ajax 函数也返回搜索词作为结果列表中的第一个结果来完成这项工作。然后用户可以选择该结果作为标签。

