Resetting Select2 value in dropdown with reset button

前端 未结 16 974
别跟我提以往
别跟我提以往 2020-12-23 13:00

What would be the best way to reset the selected item to default? I\'m using Select2 library and when using a normal button type=\"reset\", the value i

相关标签:
16条回答
  • 2020-12-23 13:50

    to remove all option value

    $("#id").empty();
    
    0 讨论(0)
  • 2020-12-23 13:56

    I'd try something like this:

    $(function(){
        $("#searchclear").click(function(){
            $("#d").select2('val', 'All');
        });
    });
    
    0 讨论(0)
  • 2020-12-23 14:00

    You can also reset select2 value using

    $(function() {
      $('#d').select2('data', null)
    })
    

    alternately you can pass 'allowClear': true when calling select2 and it will have an X button to reset its value.

    0 讨论(0)
  • 2020-12-23 14:00

    The best way of doing it is:

    $('#e1.select2-offscreen').empty(); //#e1 : select 2 ID
    $('#e1').append(new Option()); // to add the placeholder and the allow clear
    
    0 讨论(0)
  • 2020-12-23 14:00

    For me it works only with any of these solutions

    $(this).select2('val', null);
    

    or

    $(this).select2('val', '');
    
    0 讨论(0)
  • 2020-12-23 14:01

    Select2 uses a specific CSS class, so an easy way to reset it is:

    $('.select2-container').select2('val', '');
    

    And you have the advantage of if you have multiple Select2 at the same form, all them will be reseted with this single command.

    0 讨论(0)
提交回复
热议问题