Proper usage of jQuery select2's initSelection callback with remote data
Asked Answered
L

1

11

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 ids 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?

Lenten answered 2/3, 2013 at 12:46 Comment(0)
M
25

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

Middlebreaker answered 2/3, 2013 at 13:12 Comment(5)
Thanks for the reply. Umm... The issue I have is that once the form has been submitted and is redisplayed (because of a another field being in error for instance), I have lost the text variable (it is still on the server side...). Do you see my point?Lenten
why does this not work when multiple in set to false? Of course you would only use one data object etc.Inhabiter
Do you have to require the values again at the end?Wynne
demo not work, example not work .. :( i get Uncaught Error: No select2/compat/initSelectionSacaton
the select2 resources are gone this is why the demo did not work, I made update to the external files and now its ok jsfiddle.net/VpnCe/675Lifton

© 2022 - 2024 — McMap. All rights reserved.