362

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.

<div id="labels">
  <table class="config">
    <thead>
      <tr>
        <th colspan="4"; style= "padding-bottom: 20px; color:#6666FF; text-align:left; font-size: 1.5em">Control Buttons Configuration</th>
      </tr>
      <tr>
        <th>Index</th>
        <th>Switch</th>
        <th>Response Number</th>
        <th>Description</th>
      </tr>
    </thead>
    <tbody>            
      <form id="configform" name= "input" action="#" method="get">
        <tr>
          <td style="text-align: center">1</td>
          <td><img src= "static/switch.png" height="100px" width="108px"></td>
          <td id="small"><input style="background: white; color: black;" type="text" value="" id="number_one"></td>
          <td><input style="background: white; color: black;" type="text"  id="label_one"></td>
        </tr>
        <tr>
          <td style="text-align: center">2</td>
          <td><img src= "static/switch.png" height="100px" width="108px"></td>
          <td id="small"><input style="background: white; color: black;" type="text" id = "number_two" value=""></td>
          <td><input style="background: white; color: black;" type="text"  id = "label_two"></td>
        </tr>
        <tr>
          <td style="text-align: center">3</td>
          <td><img src= "static/switch.png" height="100px" width="108px"></td>
          <td id="small"><input style="background: white; color: black;" type="text" id="number_three" value=""></td>
          <td><input style="background: white; color: black;" type="text" id="label_three"></td>
        </tr>
        <tr>
          <td style="text-align: center">4</td>
          <td><img src= "static/switch.png" height="100px" width="108px"></td>
          <td id="small"><input style="background: white; color: black;" type="text" id="number_four" value=""></td>
          <td><input style="background: white; color: black;" type="text" id="label_three"></td>
        </tr>
        <tr>
          <td></td>
          <td><input type="submit" id="configsubmit" value="Submit"></td>
        </tr>
        <tr>
          <td><input type="reset" id="configreset" value="Reset"></td>
        </tr>
                  
      </form>
    </tbody>
  </table>
            
</div>

And my jQuery:

$('#configreset').click(function(){
    $('#configform')[0].reset();
});

Is there some source that I should include in my code in order for the .reset() method to work? Previously I was using:

<script src="static/jquery.min.js"></script>
<script src="static/jquery.mobile-1.2.0.min.js"></script>

and the .reset() method was working.

Currently I'm using

<script src="static/jquery-1.9.1.min.js"></script>      
<script src="static/jquery-migrate-1.1.1.min.js"></script>
<script src="static/jquery.mobile-1.3.1.min.js"></script>

Could it possibly be one of the reason?

starball
  • 20,030
  • 7
  • 43
  • 238
yvonnezoe
  • 7,129
  • 8
  • 30
  • 47
  • can you give an example of not working? is any of the fields getting reseted? – Arun P Johny May 09 '13 at 03:20
  • it's something like this but it is working fine here http://jsfiddle.net/chJ8B/ :( probably because of other parts of the script? but i have only 1 form – yvonnezoe May 09 '13 at 03:26
  • my question is whether none of the field is resetted / some are working – Arun P Johny May 09 '13 at 03:27
  • 13
    **Your HTML is invalid**. A form can't be a child of a TBODY element, and a TR can't be a child of a FORM element. Put the form tags outside the table (i.e. put the table in the form). Quite possibly the form is being moved outside the table, but the form controls are staying in the cells so they are no longer in the form. – RobG May 09 '13 at 08:33
  • @RobG :O good point! i shall try that. thank you! i could have missed this useful comment if i don't come back here to get my fiddle link :s – yvonnezoe May 14 '13 at 08:52

16 Answers16

627

you may try using trigger() Reference Link

$('#form_id').trigger("reset");
SagarPPanchal
  • 9,839
  • 6
  • 34
  • 62
  • I am using $('.profile_img_form').trigger('reset'); i have added profile_img_form named class on my form then called it. it does not reset my form and returning error message like Uncaught SyntaxError: Invalid regular expression: /(^|\.)bs\.(?:.*\.|)fileinput(\.|$)/: Kindly suggest what is issue. Thanks. – Kamlesh Sep 25 '19 at 12:22
  • @Kamlesh it should work, I have created a demo for you, click on https://jsfiddle.net/Lkt4eq9y/2/ – SagarPPanchal Sep 26 '19 at 04:25
  • Would it reset `hidden` inputs too? I wouldn't want that – Sergey Zolotarev Apr 13 '23 at 18:18
306

http://jsfiddle.net/8zLLn/

  $('#configreset').click(function(){
        $('#configform')[0].reset();
  });

Put it in JS fiddle. Worked as intended.

So, none of the aforementioned issues are at fault here. Maybe you're having a conflicting ID issue? Is the click actually executing?

Edit: (because I'm a sad sack without proper commenting ability) It's not an issue directly with your code. It works fine when you take it out of the context of the page that you're currently using, so, instead of it being something with the particular jQuery/javascript & attributed form data, it has to be something else. I'd start bisecting the code around it out and try to find where it's going on. I mean, just to 'make sure', i suppose you could...

console.log($('#configform')[0]);

in the click function and make sure it's targeting the right form...

and if it is, it has to be something that's not listed here.

edit part 2: One thing you could try (if it's not targeting it correctly) is use "input:reset" instead of what you are using... also, i'd suggest because it's not the target that's incorrectly working to find out what the actual click is targeting. Just open up firebug/developer tools, whathave you, toss in

console.log($('#configreset'))

and see what pops up. and then we can go from there.

FullOnFlatWhite
  • 3,642
  • 2
  • 18
  • 23
  • no conflicting ID :( i'm trying to select layer by layer and check if the click works – yvonnezoe May 09 '13 at 02:16
  • 1
    hmm seems like the click doesnt work! i added `$('#ptest').html("clicked reset")` in the click(function(){}); where it should show "clicked reset" but it didnt show up – yvonnezoe May 09 '13 at 02:22
  • i have a question here. everytime i use console.log, i have no idea where to look out for it. i'm using Python IDLE and a terminal to run the python script. the javascript is in it. anyway, when i use `alert($('#configform')[0]), it gives me [object HTMLFormElement] – yvonnezoe May 09 '13 at 02:33
  • and the browser i'm using is midori in raspberry pi. :/ can't use any debugger i guess... – yvonnezoe May 09 '13 at 02:34
  • 1
    Try using alert(JSON.stringify($'#configform')[0])). Alert doesn't care much for pretty printing objects (or telling you what's in it). It just lets you know that it's an object. – FullOnFlatWhite May 09 '13 at 02:41
  • Re: RaspPi, you could always use Chromium or [Firebug Lite's bookmarklet](http://getfirebug.com/firebuglite) in Midori to access a console. – FullOnFlatWhite May 09 '13 at 02:45
  • do i need to install anything for JSON? it doesn't alert – yvonnezoe May 09 '13 at 02:53
  • no. you shouldn't have to. I edited it from the original one (i had an underscore for some reason?). alert(JSON.stringify($('#configform')[0])) should be the right syntax for it. – FullOnFlatWhite May 09 '13 at 03:11
  • oh it gave me an empty string `{}` – yvonnezoe May 09 '13 at 03:23
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/29628/discussion-between-tadiou-and-yvonnezoe) – FullOnFlatWhite May 09 '13 at 03:25
  • what does the `[0]` do? – Dylan Czenski Jul 05 '16 at 19:24
  • 1
    @DylanChensky the magic of jQuery is that everything is a set (array). Just as if you were using a regular array in jQuery `[0]` selects the first element. But in jQuery, it selects the actual html of the element. So, `[0]` is giving you the html, which allows you to call the html, not jQuery, method called `reset`. See @kevin 's answer below for more information. – FullOnFlatWhite Jul 10 '16 at 12:59
  • @tadiou May I ask you one question please! What is the meaning of $('#form_id') **[0]** <--? – Huy Le Nov 28 '16 at 10:04
  • @HuyLe $('#form_id') is an object, it's a jQuery object. Performing `[0]` on it is giving you the HTML dom element instead of the jQuery object. In the same way that you would do `document.getElementById()`, the `[0]` just grabs the underlying element in the same way you would with raw javascript. – FullOnFlatWhite Nov 28 '16 at 15:58
  • This answer doesn't address the actual issue and will not work for the OP. The problem is that due to the invalid markup, none of the form controls are inside the form. This code will not reset the controls. – RobG Jan 31 '17 at 20:17
  • @RobG, I actually discussed this with the OP privately where this was solved almost 4 years ago. :) For the most part, people having this problem don't have HTML issues like this. – FullOnFlatWhite Feb 01 '17 at 15:16
113

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()
Kevin
  • 6,539
  • 5
  • 44
  • 54
  • 1
    It works and I'm in agree, jQuery has no reset() method. You can see how to do it with native JavaScript at w3school doc: http://www.w3schools.com/jsref/met_form_reset.asp – serfer2 Jun 26 '14 at 08:20
  • 2
    I would like to note that this will only _reset_ the form, not clear it. I.e, if the form had values sent with the request, those will be restored. – Protector one Dec 10 '14 at 12:57
  • I would like to add comment regarding placeholder, initial render of form, form elements have values of placeholder, after this reset regardless of placeholder shown again but value become blank, so be care full while form validation. I was adding generic form validation to check placeholder value is default. – Ramratan Gupta Jan 06 '16 at 06:18
54

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).

Nick F
  • 9,781
  • 7
  • 75
  • 90
35

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 use this if you have different types registered with different events

$('form#myform select, form input[type=checkbox]').trigger("change"); //Line2
Ali Jamal
  • 1,383
  • 1
  • 13
  • 20
31

jQuery does not have reset() method; but native JavaScript does. So, convert the jQuery element to a JavaScript object by either using :

$("#formId")[0].reset();

$("#formId").get(0).reset();

We may simply use Javascript code

document.getElementById("formid").reset();
mohammed wazeem
  • 1,310
  • 1
  • 10
  • 26
Vivek Pawar
  • 339
  • 3
  • 5
29

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.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • u mean simply just that line will do? o.O so is my html above correct? – yvonnezoe May 09 '13 at 02:31
  • Define "not working". What error do you get? What isn't working? Reset buttons have been a part of HTML forms forever, they work. – RobG May 09 '13 at 08:31
  • 1
    "not working" - it does not reset anything, no change was seen in the form. – yvonnezoe May 10 '13 at 00:57
  • 1
    Something to note is that "reset" does not mean "my form is cleared". What the semantics of "reset" actually do is return all of the "form" elements back to their original "value" attributes. That confused me for a few minutes at least! – jocull Oct 12 '16 at 20:27
  • @jocull—when all else fails, there is always either the [*W3C*](http://w3c.github.io/html/sec-forms.html#reset-button-state-typereset) or [*WHATWG*](https://html.spec.whatwg.org/multipage/forms.html#reset-button-state-(type=reset)) version of the HTML standard. ;-) – RobG Oct 12 '16 at 22:55
  • @yvonnezoe all of your form fields, inputs, buttons, etc. need to be nested INSIDE the
    element, otherwise it won't work.
    – john_h Jan 31 '17 at 15:11
  • this solution works for me @RobG, type=reset not works for me because it has another function for close modal, so i add this onclick="this.form.reset();" and it worked,Thanks! – bdalina Oct 16 '17 at 14:51
  • Wonderfull solution, but I'd like to note that part of the reason I came to this SO question was that the input[type=reset] was not properly triggering a form reset, due to an event bound elsewhere using `preventDefault()`. – Lazerbeak12345 May 08 '20 at 15:15
  • 1
    @Lazerbeak12345—unfortunately almost all web pages are now virtually applications that overwrite just about all default functionality of HTML DOMs. Hence even very simple pages are now many megabytes of script and libraries where they were once 20 or 30k of HTML with a little script. Not only is processing power and bandwidth squandered, but accessibility and usability are generally very poor. :-( – RobG May 08 '20 at 22:33
24

I've finally solve the problem!! @RobG was right about the form tag and table tag. the form tag should be placed outside the table. with that,

<td><input type="reset" id="configreset" value="Reset"></td>

works without the need of jquery or anything else. simple click on the button and tadaa~ the whole form is reset ;) brilliant!

yvonnezoe
  • 7,129
  • 8
  • 30
  • 47
  • 3
    you can usually confirm this is happening by inspecting the source code (not viewing the page source, as that will show what was generated, but rather using something like Developer Tools F12), which shows you "what the browser sees" -- in which case it would [show you](http://jsfiddle.net/chJ8B/) (in Chrome, at least) that the `form` tag had been automatically closed at the beginning of the `tbody`, excluding the input elements. – drzaus Feb 13 '14 at 18:31
  • check the compatibility: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/reset – Diego Avila Jul 03 '18 at 19:12
19

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');
});
fausto
  • 305
  • 3
  • 5
  • [Same comment as on aldrien's answer](http://stackoverflow.com/questions/16452699/how-to-reset-a-form-using-jquery-with-reset-method#comment45714787_28712102) – Dan Dascalescu Aug 22 '15 at 08:57
13

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("");
aldrien.h
  • 3,437
  • 2
  • 30
  • 52
7

A quick reset of the form fields is possible with this jQuery reset function.

when you got success response then fire below code.

$(selector)[0].reset();

Kiran Kanzar
  • 329
  • 1
  • 5
  • 14
4

You can just add an input type = reset with an id = resetform like this

<html>
<form>
<input type = 'reset' id = 'resetform' value = 'reset'/>
<!--Other items in the form can be placed here-->
</form>
</html>

then with jquery you simply use the .click() function on the element with the id = resetform as follows

<script> 
$('#resetform').click();
</script>

and the form resets Note: You can also hide the reset button with id = resetform using your css

<style>
#resetform
{
display:none;
}
</style>
Chuksy
  • 272
  • 2
  • 6
3

Here is simple solution with Jquery. It works globally. Have a look on the code.

$('document').on("click", ".clear", function(){
   $(this).closest('form').trigger("reset");
})

Add a clear class to a button in every form you need to reset it. For example:

<button class="button clear" type="reset">Clear</button>
Ijharul Islam
  • 1,429
  • 11
  • 13
2
<button type="reset">Reset</reset>

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

luminancedesign
  • 362
  • 2
  • 5
0

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.

ic3b3rg
  • 14,629
  • 4
  • 30
  • 53
  • The only other problem I can think of is that you have another form with the same id (`configform`). You should do some investigation using the console. First try `$`. If you're using Chrome, typing `$` in the console will activate a context-sensitive list if jQuery is loaded. If you type `$` and press return, it will evaluate to a function if jQuery is loaded. Next try `$("#configform")`. Right-click on the result and select `Reveal in Elements panel`. – ic3b3rg May 09 '13 at 12:38
  • thank you :) but i do not have chrome. is it the same way to do it using firebug? (i have it installed but never use it before) – yvonnezoe May 10 '13 at 00:59
-1

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("");
        });
    });
RainyTears
  • 171
  • 4
  • 2
    There seems to be a lot of framework-specific code here. I recommend avoiding such things when answering questions on SO, as the question didn't specify that they were using any framework aside from jQuery – Lazerbeak12345 May 08 '20 at 15:20