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/
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/
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