问题
Here is my select2 multiple select with ajax.
Initially i am setting some values in the initselection like this
initSelection : function (element, callback) {
var data = {id: 4, zipcode: "00602"};
callback(data);
};
And then i am doing the ajax selection.
But i can't able to sustain the old values. i.e., when i type the new selection, the old values are replaced instead of appending .
Here is my entire code.
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
});
I am using select2 4 version.
Here is the 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;
}
What should i do to retain the old values and append it to the new values.
回答1:
In processResults
method you need to add your initial data in return
:
data.items[data.items.length] = initialdata;
results: data.items
initialdata
has to be in global/object scope.
来源:https://stackoverflow.com/questions/37475968/how-to-append-jquery-select2-values-with-initselection