I know this is an old question, but I had troubles with it too.
Since the select2 is filled when user inputs some text via AJAX, it starts empty. So the previous answers of the type .val('')
don't apply.
For example:
$('#e6').val('1'); // Select the option with a value of '1'
$('#e6').trigger('change'); // Notify any JS components that the value changed
this won't work since there is no .val
to select from.
Then you need to preload some data to the select2. The selected answer which tries to preload the data did not work for me:
$("#e6").select2('data', {id: '1049', text: 'MyLabel'});
(I guess the code and behavior of the plugin has changed since the answer was made and accepted)
Then you solve this in 2 ways:
You can force it to be preloaded by the AJAX using the code in the documentation.
You can preload data and select it with JS. In my case I needed this select2 prefilled with preselected elements while maintaining the AJAX search.
I used the following:
select2 = $('#e6');
var option = new Option('MyLabel', 1049, true, true); //The true vars are for preselecting
select2.append(option); //You can repeat this and the previous line for multiselect
select2.trigger('change'); //Call change event so the control updates
The same in fewer lines:
var option = new Option('MyLabel', 1049, true, true); //The true vars are for preselecting. 1049 is the id.
$('#e6').append(option).trigger('change'); //Append option and call change event
Hope this helps someone.