how to change select2 value programmatically

爱⌒轻易说出口 提交于 2019-12-08 14:29:51

问题


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


回答1:


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

is the right way, see here




回答2:


$('#select_id').select2('val', selectedValue);



回答3:


For Select2 with Ajax call, I struggled with lot of options, but none worked. Then i came to following solution, which works like charm $("#select_id").html($("").val('val').text('text')).trigger("change");




回答4:


If you, like me, have added a custom handler for the select2:selecting event the correct complete answer to changing a value and triggering the custom select2 event would be:

$('#select_id').val('val').trigger('change').trigger({
     type: 'select2:event_name', // It worked for me with select2:selecting and select2:select
     params: {
       args: { // Only use 'args' if using select2:selecting, select2:select does not use it
         data: varWithEventData
       }
     }
});


来源:https://stackoverflow.com/questions/38773041/how-to-change-select2-value-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!