I have a select2 box in bootstrap modal, I want to change the value of the select2 box but it didn't work.
I tried every single solution in previous posts and results but none of them got it work.
I use select2 4.0.2, I tested:
$('#select_id').val('val').trigger('change.select2'); $('#select_id').val('val').trigger('change'); $('#select_id').val('val').change()
It works one or two times then it stops working (randomly)
It works fine only when I change the select2 back to 3.x.x
Selecting options. To programmatically select an option/item for a Select2 control, use the jQuery .val() method: You can also pass an array to val make multiple selections: Select2 will listen for the change event on the <select> element that it is attached to.
To set initial values you need to add the necessary options tag to the select element with jQuery, then define these options as selected with select2's val method and finally trigger select2's 'change' event. The third boolean argument tells select2 to trigger the change event. Show activity on this post.
As Kevin pointed out, if you want to change the items in the SELECT after Select2 has been created you only need to manipulate the OPTIONs inside the SELECT and trigger the CHANGE event. Select2 will react to the changes and update accordingly.
Dynamic option creation In addition to a prepopulated menu of options, Select2 can dynamically create new options from text input by the user in the search box. This feature is called "tagging". To enable tagging, set the tags option to true:
$('#select_id').val('val').trigger('change');
is the right way, see here
$('#select_id').select2('val', selectedValue);
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