Resetting Select2 value in dropdown with reset button

前端 未结 16 975
别跟我提以往
别跟我提以往 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 14:02

    If you have a populated select widget, for example:

    <select>
        <option value="1">one</option>
        <option value="2" selected="selected">two</option>
        <option value="3">three</option>
        ...
    

    you will want to convince select2 to restore the originally selected value on reset, similar to how a native form works. To achieve this, first reset the native form and then update select2:

    $('button[type="reset"]').click(function(event) {
        // Make sure we reset the native form first
        event.preventDefault();
        $(this).closest('form').get(0).reset();
        // And then update select2 to match
        $('#d').select2('val', $('#d').find(':selected').val());
    }
    
    0 讨论(0)
  • 2020-12-23 14:02
        // Store default values
        $('#filter_form [data-plugin="select2"]').each(function(i, el){
            $(el).data("seldefault", $(el).find(":selected").val());
            });
    
        // Reset button action
        $('#formresetbtn').on('click', function() {
            $('#filter_form [data-plugin="select2"]').each(function(i, el){
                $(el).val($(el).data("seldefault")).trigger('change');
                });
            });
    
    0 讨论(0)
  • 2020-12-23 14:03

    you can used:

    $("#d").val(null).trigger("change"); 
    

    It's very simple and work right! If use with reset button:

    $('#btnReset').click(function() {
        $("#d").val(null).trigger("change"); 
    });
    
    0 讨论(0)
  • 2020-12-23 14:04

    Just to that :)

    $('#form-edit').trigger("reset");
    $('#form-edit').find('select').each(function(){
      $(this).change();
    });
    
    0 讨论(0)
提交回复
热议问题