how to change select2 value programmatically

后端 未结 4 1327
醉话见心
醉话见心 2021-01-17 07:13

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 resul

相关标签:
4条回答
  • 2021-01-17 07:49

    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");

    0 讨论(0)
  • 2021-01-17 07:52
    $('#select_id').val('val').trigger('change');
    

    is the right way, see here

    0 讨论(0)
  • 2021-01-17 08:00
    $('#select_id').select2('val', selectedValue);
    
    0 讨论(0)
  • 2021-01-17 08:08

    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
           }
         }
    });
    
    0 讨论(0)
提交回复
热议问题