Dynamically add item to jQuery Select2 control that uses AJAX

前端 未结 9 1598
梦毁少年i
梦毁少年i 2020-11-29 02:44

I have a jQuery Select2 control that uses AJAX to populate:



         


        
9条回答
  •  既然无缘
    2020-11-29 03:13

    In case of Select2 Version 4+

    it has changed syntax and you need to write like this:

    // clear all option
    $('#select_with_blank_data').html('').select2({data: [{id: '', text: ''}]});
    
    // clear and add new option
    $("#select_with_data").html('').select2({data: [
     {id: '', text: ''},
     {id: '1', text: 'Facebook'},
     {id: '2', text: 'Youtube'},
     {id: '3', text: 'Instagram'},
     {id: '4', text: 'Pinterest'}]});
    
    
    
    //  append option
    $("#select_with_data").append('');
    $("#select_with_data").val('5');
    $("#select_with_data").trigger('change');
    

提交回复
热议问题