这是我的select2多项选择ajax。
最初我在initselection中设置了一些像这样的
initSelection : function (element, callback) {
var data = {id: 4, zipcode: "00602"};
callback(data);
};
然后我正在进行ajax选择。
但我无法维持旧的价值观。即,当我键入新选择时,旧值将被替换而不是附加。
这是我的整个代码。
var $select = $('#firstList');
$select.select2({
placeholder : "Enter Pincode",
allowClear : true,
cache : true,
initSelection : function(element, callback) {
var data = {
id : 4,
zipcode : "00602"
};
callback(data);
},
ajax : {
url : "../getZipList",
type : "POST",
contentType : "application/json; charset=utf-8",
delay : 250,
data : function(params) {
//console.log(params)
return {
q : params.term, // search term
page : params.page
};
},
processResults : function(data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results : data.items
};
//console.log(data.it)
},
cache : true
},
escapeMarkup : function(markup) {
return markup;
}, // let our custom formatter work
minimumInputLength : 1,
templateResult : formatRepo, // omitted for brevity, see the source of this page
templateSelection : formatRepoSelection // omitted for brevity, see the source of this page
});
我正在使用select2 4版本。
这是formatrepo
function formatRepo(repo) {
if (repo.loading)
return repo.text;
var markup = '<div class="clearfix">' + '<div clas="col-sm-10">' + '<div class="clearfix">' + '<div class="col-sm-6">' + repo.zipcode + '</div>' + '</div>';
markup += '</div></div>';
return markup;
}
function formatRepoSelection(repo) {
console.log(repo);
return repo.zipcode;
var cur_val = $('#zipcodeCollection').val();
console.log(repo.zipcode);
if (cur_val) {
$('#zipcodeCollection').val(cur_val + "," + repo.zipcode);
} else {
$('#zipcodeCollection').val(repo.zipcode);
}
return repo.zipcode;
}
我该怎么做才能保留旧值并将其附加到新值。
答案 0 :(得分:0)
在processResults
方法中,您需要在return
中添加初始数据:
data.items[data.items.length] = initialdata;
results: data.items
initialdata
必须在全局/对象范围内。