Programmatic selection of select2 which retrieves its data via Ajax
The only way to achieve this, is to first add an <option>
to the select dom with the data you would like to select, and right afterwards, select it like you would do with a regular select box. This was the official answer from kevin-brown also, on their github project page.
https://github.com/select2/select2/issues/3273
So, basicaly, if you know what would you like to select, you can easily create an <option>
element from it, add it to the original select box, and then select it by it's value:
var option=jQuery("<option>").attr("value","your_id_here").html("your_text_here");jQuery("selectbox").append(option);jQuery("selectbox").val("your_id_here").trigger("change");
I would also love to know a full answer to this, but here's a partial solution:
$('#select2-control-id').val('item-id').trigger('select2:select').trigger('change');
This only seems to work if the select2
has already loaded the item you're asking for - i.e. it's one you've already clicked on.
Not only do you have to have manually opened the dropdown so it will load the first page of items via AJAX - you also have to have actually clicked on the one you want to programmatically select later.
This appears to be because it only adds <options>
to the underlying select
element when you actually click on them.
I can't see a way to programmatically tell select2
to load the first page of AJAX results.
It's easy to manipulate the hidden <select/>
box as:
//set first option as selected $("select [value='0']").attr("selected","selected");$("select").trigger("change");