Clear dropdown using jQuery Select2

前端 未结 15 1930
情深已故
情深已故 2020-11-28 11:35

I\'m trying to programmatically clear a drop down using the fantastic Select2 library. The drop down is dynamically filled with a remote ajax call using the Select2 qu

相关标签:
15条回答
  • 2020-11-28 12:03

    Using select2 version 4 you can use this short notation:

    $('#remote').html('').select2({data: {id:null, text: null}});
    

    This passes a json array with null id and text to the select2 on creation but first, with .html('') empties the previously stored results.

    0 讨论(0)
  • 2020-11-28 12:04

    Since none of them all worked for me (select2 4.0.3) is went the std select way.

    for(var i = selectbox.options.length - 1 ; i >= 0 ; i--)
        selectbox.remove(i);
    
    0 讨论(0)
  • 2020-11-28 12:07

    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'}]});
    
    0 讨论(0)
  • 2020-11-28 12:07

    This solved my problem in version 3.5.2.

    $remote.empty().append(new Option()).trigger('change');
    

    According to this issue you need an empty option inside select tag for the placeholder to show up.

    0 讨论(0)
  • 2020-11-28 12:07

    These both work for me to clear the dropdown:

    .select2('data', null)
    .select2('val', null)
    

    But important note: value doesn't get reset, .val() will return the first option even if it's not selected. I'm using Select2 3.5.3

    0 讨论(0)
  • 2020-11-28 12:10

    This is how I do:

    $('#my_input').select2('destroy').val('').select2();
    
    0 讨论(0)
提交回复
热议问题