2
這裏是我的select2多選與ajax。如何附加jQuery的select2值與initSelection
最初我在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
});
我使用選擇2 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;
}
我應該做的,保留舊值,並將它附加到新的價值觀。