I am using select2 version 4.0, and I am trying to make a programmatic selection to a select box which gets its data from an ajax call.
In the documentation, I found how to set a value programmatically to a regular select2, but I can't figure out how to do this with an ajax select.
If I remember correctly, in the old version, you could set the current value by passing a data to the select2 with this command:
jQuery("selectbox").select2("data", data)
I've tried this, and sent a data object with, id, text and result, but nothing visible happens, and when I query the status of the select box, to see the selected values, it returns null.
Was this option removed, or simply changed? Where can I find this in the documentation, or how could I achieve the desired behaviour?
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");
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