Виберіть 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
}
}
},
maximumSelectionLength: 3,
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
};
}
},
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);
},
maximumSelectionSize: 3,
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"
}
]
ОНОВЛЕНО 22.01.2015:
Виправлено jsfiddle: http://jsfiddle.net/X6V2s/66/
ОНОВЛЕНО 09.09.2015:
З 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({
tags: true,
ajax: {
url: "https://api.myjson.com/bins/444cr",
processResults: function (data, page) {
return {
results: data
};
}
}
});