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

前端 未结 16 1196
清酒与你
清酒与你 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 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).

提交回复
热议问题