Reputation: 41
At the moment I have a dropdown that works with ajax request to the server, but it also be nice to attach some default options on select2 initialization. With initSelection function I only can attach one option, but not full preloaded array. I was also trying to use data option but it's doesn't work too. Here is my code:
$("#address-select2").select2({
placeholder: "--- ' . t('I\'ll add new address') . ' ---",
minimumInputLength: 3,
ajax: {
url: "/ajax/address_autocomplete/from",
dataType: "json",
type: "POST",
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return {results: data.addresses};
}
},
initSelection: function (element, callback) {
$.ajax("/ajax/address_autocomplete/from/100", {
dataType: "json"
}).done(function(data) {
callback(data.addresses[0]);
});
},
formatResult: function (address) {
return "<span class=\"dropdown-element\">" + address.text + "</span>";
},
formatSelection: function (address) {
return address.text;
},
formatNoMatches: function () { return "' . t('No result found!') . '";},
formatSearching: function () { return "' . t('Searching...') . '"; },
formatLoadMore: function (pageNumber) { return "' . t('Loading results...') . '"; },
dropdownCssClass : "bigdrop"
});
Upvotes: 2
Views: 6699
Reputation: 379
please do not pass callback(data.addresses[0]);
please pass array directly like this callback(data.addresses);
it should work i have done it.
Upvotes: 1