Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change select2 value programmatically

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

like image 986
Chaanbi Kada Avatar asked Aug 04 '16 16:08

Chaanbi Kada


People also ask

How do I programmatically select an option in Select2?

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.

How to set initial values of selected options in select event?

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.

How to change items in Select2 after it has been created?

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.

How do I create dynamic options in Select2?

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:


2 Answers

$('#select_id').val('val').trigger('change'); 

is the right way, see here

like image 80
Dario Avatar answered Sep 20 '22 11:09

Dario


$('#select_id').select2('val', selectedValue); 
like image 26
igasparetto Avatar answered Sep 23 '22 11:09

igasparetto