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

前端 未结 16 1168
清酒与你
清酒与你 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:58

    According to this post here, jQuery has no reset() method; but native JavaScript does. So, convert the jQuery element to a JavaScript object by either using :

    $("#formId")[0].reset()
    // or
    $("#formId").get(0).reset()
    
    0 讨论(0)
  • 2020-11-22 18:01

    A reset button doesn't need any script at all (or name or id):

    <input type="reset">
    

    and you're done. But if you really must use script, note that every form control has a form property that references the form it's in, so you could do:

    <input type="button" onclick="this.form.reset();">
    

    But a reset button is a far better choice.

    0 讨论(0)
  • 2020-11-22 18:03

    This is one of those things that's actually easier done in vanilla Javascript than jQuery. jQuery doesn't have a reset method, but the HTML Form Element does, so you can reset all the fields in a form like this:

    document.getElementById('configform').reset();
    

    If you do this via jQuery (as seen in other answers here: $('#configform')[0].reset()), the [0] is fetching the same form DOM element that you would get directly via document.getElementById. The latter approach is both more efficient and simpler though (since with the jQuery approach you first get a collection and then have to fetch an element from it, whereas with the vanilla Javascript you just get the element directly).

    0 讨论(0)
  • 2020-11-22 18:03
    <button type="reset">Reset</reset>
    

    Simplest way I can think off that is robust. Place within the form tag.

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