select2 ajax demo,javascript - Tagging with AJAX in select2 - Stack Overflow

Select v4

HTML:

tag1

tag2

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

Example with some improvements:

html:

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"

}

]

UPDATED 2015-01-22:

UPDATED 2015-09-09:

With Select2 v4.0.0+ it became easier.

Select v4.0.0

HTML:

tag1

tag2

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

};

}

}

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值