I use jQuery select2 plugin in order to retrieve postcodes using the provided ajax callback function as follows:
$(document).ready(function() {
$("#postcodes").select2({
placeholder : "Search for a postcode",
multiple : true,
minimumInputLength : 3,
ajax : {
url : "/bignibou/utils/findGeolocationPostcodeByPostcodeStartingWith.json",
dataType : 'json',
data : function(term) {
return {
postcode : term
};
},
results : function(data) {
console.log(data);
return {
results : $.map(data, function(item) {
return {
id : item.id,
text : item.postcode
};
})
};
}
}
});
});
Once two postcodes are selected I get the resulting hidden input
in the DOM:
<input type="hidden" class="bigdrop select2-offscreen" id="postcodes" style="width:600px" name="familyAdvertisement.postcodes" value="4797,4798" tabindex="-1">
The issue I have is that once the form is redisplayed (for instance in the event of some other controls being in error), the selections (i.e. the two postcodes and especially the text
) don't show in the form although the hidden input
does have the two values (i.e. 4797 and 4798, which are the id
s for the postcode).
I am not sure if I have to do another ajax round trip when the form is redisplayed or if there is a better way to go.
Can anyone please advise?
The initSelection method has to pass the values which has to be present in the select2
Ex:
$("#postcodes").select2({
placeholder : "Search for a postcode",
multiple : true,
minimumInputLength : 1,
data:[],
initSelection : function (element, callback) {
var data = [{id:1,text:'bug'},{id:2,text:'duplicate'}];
callback(data);
}
}).select2('val', ['1', '2']);
Demo: Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With