How to reset a form using jQuery with .reset() method

前端 未结 16 1189
清酒与你
清酒与你 2020-11-22 17:28

I had working code that could reset my form when I click on a reset button. However after my code is getting longer, I realize that it doesn\'t work anymore.



        
相关标签:
16条回答
  • 2020-11-22 17:51

    You can use the following.

    @using (Html.BeginForm("MyAction", "MyController", new { area = "MyArea" }, FormMethod.Post, new { @class = "" }))
    {
    <div class="col-md-6">
        <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12">
            @Html.LabelFor(m => m.MyData, new { @class = "col-form-label" })
        </div>
        <div class="col-lg-9 col-md-9 col-sm-9 col-xs-12">
            @Html.TextBoxFor(m => m.MyData, new { @class = "form-control" })
        </div>
    </div>
    <div class="col-md-6">
        <div class="">
            <button class="btn btn-primary" type="submit">Send</button>
            <button class="btn btn-danger" type="reset"> Clear</button>
        </div>
    </div>
    }
    

    Then clear the form:

        $('.btn:reset').click(function (ev) {
            ev.preventDefault();
            $(this).closest('form').find("input").each(function(i, v) {
                $(this).val("");
            });
        });
    
    0 讨论(0)
  • 2020-11-22 17:52

    By using jquery function .closest(element) and .find(...).

    Getting the parent element and looking for the child.

    Finally, do the function needed.

    $("#form").closest('form').find("input[type=text], textarea").val("");
    
    0 讨论(0)
  • 2020-11-22 17:54

    I use this simple code:

    //reset form 
    $("#mybutton").click(function(){
        $("#myform").find('input:text, input:password, input:file, select, textarea').val('');
        $("#myform").find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
    });
    
    0 讨论(0)
  • 2020-11-22 17:54

    Your code should work. Make sure static/jquery-1.9.1.min.js exists. Also, you can try reverting to static/jquery.min.js. If that fixes the problem then you've pinpointed the problem.

    0 讨论(0)
  • 2020-11-22 17:57

    you may try using trigger() Reference Link

    $('#form_id').trigger("reset");
    
    0 讨论(0)
  • 2020-11-22 17:57

    First line will reset form inputs

    $('form#myform').trigger("reset"); //Line1
    $('form#myform select').trigger("change"); //Line2
    

    Second one will reset select2

    Optional: You can user this if you have different types registered with different events

    $('form#myform select, form input[type=checkbox]').trigger("change"); //Line2
    
    0 讨论(0)
提交回复
热议问题