[英]How to append jquery select2 values with initSelection
這是我的使用ajax的select2多重選擇。
最初,我在像這樣的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;
}
我應該怎么做才能保留舊值並將其附加到新值。
在processResults
方法中,您需要添加初始數據作為return
:
data.items[data.items.length] = initialdata; results: data.items
initialdata
必須在全局/對象范圍內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.