Jquery – How to initSelection() on a tag list of id/label pairs

jqueryjquery-select2

I'm initialising a Select2 tag list as follows:

<input type="text" name="users" value="" id="users" class="span3"  />

$("#users").select2({
    tags            : [
        {'id':1, 'text':'Ben'},  
        {'id':22, 'text':'Andrea'},  
        {'id':23, 'text':'Tim'},
        {'id':7, 'text':'Matt'}
    ]
    ,tokenSeparators    : [",", " "]
}).on('change', function(event){
    console.log(event.val.toString());
});

… which works a treat, when the input box is empty to begin with. Selecting people by name gives me back a simple array of ID's that I can send back to the database.

However, I'm confused about how I should initialise this list with an existing selection. Let's say I load the page with Ben and Andrea already selected:

<input type="text" name="users" value="Ben, Andrea" id="users" class="span3"  />

I can see that Select2 has an initSelection() method, but I'm unsure how I'd use it. Obviously the example above is wrong, as I'm not passing the ID along with the person name – but how should I be passing that data in? And what should my implementation of the initSelection callback function look like in order to correctly initialise Select2 from it?

Best Answer

Problem solved:

https://groups.google.com/forum/#!topic/select2/3UN3DSiv4lo

You can pass an list of ID's, either in the input value or via a val() call.