Im using the Select2 jQuery plugin (v4.0.3) for a project im working on. The select2 instance is ajax sourced, and I was wondering i there is a way to programmatically select options.
I was previously able to set the value via:
$('#input-field').val(['123','456']).trigger('change')
When it was not ajax sourced. And now I need to get this working with an ajax sourced Select2 instance.
I created a jsFiddle instance, just so you can see what I mean. Clicking Set Values should select 2 values in the select2 instance.
Thanks!
P.S. I even tried setting the tags
option to true
, so any value can get selected (even if its not a result from the AJAX query), and it still doesnt work
It appears that you can't programmatically select something that hasn't been previously searched and selected from the dropdown.
Select2, when using AJAX data, appears to work by adding previously unknown options to the underlying select
element when they're discovered. .val()
is trying to add the items you want, but only the ones that already exist can be added and the rest are ignored. Select2 then gets the change
event and adjusts the render accordingly.
This should at least send you in a useful direction:
$('#set-selected').click(function(e){
e.preventDefault();
var $select = $('.js-data-example-ajax');
var targets = ["28200583","3620194"];
targets.forEach(function(v,i,a){
if(!$('option[value='+v+']',$select).length) {
$select.append('<option value="'+v+'">'+v+'</option>');
}
});
$select.val(targets).trigger('change');
});
Usually the situation with these UI libraries is that you manipulate the control the same way you initialize it, via calls to .select2()
in this case. However I'm unable to find a command in that form that does what you need in this scenario.