Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prefill select2 field with no data

I am using a select2 just for the tokenizing. I do not think I ever want to add options to the field. I would like to use the return value of an ajax call to pre-populate some entered items.

The select2 is pretty simple:

$("#select2-bug-input").select2({
            tags:[],
            tokenSeparators: [",", " "],
            placeholder: "Enter Anything(s)",
            initSelection: function(element, callback) {}
        });

To rephrase that I believe I am not interesting in using val, data, or tags to allow new selections. I want it to appears as if the user has already typed in 2+ values.

http://jsfiddle.net/BTgr8/

like image 502
user2466803 Avatar asked Jan 25 '26 05:01

user2466803


1 Answers

I am not sure why you use that specific HTML you provided in the fiddle.

The example below works with the initSelection option. The trick is to set a value in the input element. Only then the initSelection will be triggered.

HTML:

<input id="select2example" type="hidden" value="1,1,2">

JS:

    $(document).ready(function () {

        var data = [{
            id: 1,
            text: "A"
        }, {
            id: 2,
            text: "B"
        }, {
            id: 3,
            text: "C"
        }];

        $('#select2example').select2({
            multiple: true,
            data: data,//you can replace this by an ajax call to get the data in your select2
            initSelection: function (element, callback) {
                var data = [{ id: 1, text: 'A' }, { id: 3, text: 'C' }]; //you can replace this by a second ajax call to get your initial data
                callback(data);
            }
        });
    });

http://jsfiddle.net/e0ybe9qb/

like image 128
Tom Kluskens Avatar answered Jan 26 '26 20:01

Tom Kluskens