Alex
Alex

Reputation: 7688

select2 default values incomplete

I have an input with the following value: e22,e33,e35

On that input, I want to initialize select2 with the default values mentioned above. The code I use to try and do so, is the following:

$('input[name="postal_code"]').select2({
    placeholder: 'search a postal code',
    allowClear: true,
    minimumInputLength: 2,
    maximumSelectionSize: $maxInput,
    multiple: true,
    tokenSeparators: [",", " "],
    createSearchChoice: function(term, data) {
        if ($(data).filter(function() {
            return this.text.localeCompare(term)===0;
        }).length === 0) {
            return {
                id: term,
                text: term
            };
        } 
    },
    ajax: {
        url: $url,
        dataType: "json",
        data: function(term, page) {
            return {
                query: term
            };
        },
        results: function(data, page) {
            console.log(data);
            return {
                results: data,
            };
        }
    },
    initSelection: function(element, callback) {
        var data = [];
        $(element.val().split(",")).each(function(i, v) {
            console.log(v);
            data.push({
                text: v
            });
        });
        console.log(data);
        callback(data);
    }
});

The problem is that the input, after select initialization, instead of having the following tags: , , ; I only have

Any ideas, why the rest are cut off?

JSFiddle: http://jsfiddle.net/alleks/fMXxL/

Upvotes: 2

Views: 937

Answers (1)

Trevor
Trevor

Reputation: 16116

It looks like the reason it's not working is because It is looking for a unique id for each object. If we add an id to each object then it works...

initSelection: function(element, callback) {
    var data = [];
    var counter = 1;
    $(element.val().split(",")).each(function(i, v) {
        console.log(v);
        data.push({
            id: counter,
            text: v
        });
        counter++;
    });
    console.log(data);
    callback(data);
}

However with the way the data is initialized If I type in the field and type my selection and hit space or , its not creating a new tag...

I had more luck with that using the tags: attribute to return your data array here is an example.

http://jsfiddle.net/bM9C9/

Not sure if the above example will help but thought I would include it just in case you can initialize your data using tags:

Upvotes: 1

Related Questions