168

I am looking for a jQuery function that will clear all the fields of a form after having submitted the form.

I do not have any HTML code to show, I need something generic.

Can you help?

Thanks!

Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
DiegoP.
  • 45,177
  • 34
  • 89
  • 107
  • 2
    A very simple solution is to do the following, var originalForm = $("#myForm#).html(); At the time where you press Cancel button or Submit button, the last command should be $("#myForm").html(originalForm); This will reset all the fields to their original state as they were defined in the HTML ... – rac3b3nn0n Dec 09 '16 at 12:52
  • Reset is a simple solution you might be looking for. – Md Ashraful Islam Aug 05 '20 at 16:59

11 Answers11

395

Note: this answer is relevant to resetting form fields, not clearing fields - see update.

You can use JavaScript's native reset() method to reset the entire form to its default state.

Example provided by Ryan:

$('#myForm')[0].reset();

Note: This may not reset certain fields, such as type="hidden".

UPDATE

As noted by IlyaDoroshin the same thing can be accomplished using jQuery's trigger():

$('#myForm').trigger("reset");

UPDATE

If you need to do more than reset the form to its default state, you should review the answers to Resetting a multi-stage form with jQuery.

ktamlyn
  • 4,519
  • 2
  • 30
  • 41
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
  • 22
    More specifically: `$('#myForm')[0].reset();` – Ryan Burney Apr 29 '12 at 17:47
  • 18
    Reset doesn't clear a form, it simply sets the form values to their default which may or may not be "". Most of the other answers on this page are better. – ktamlyn Feb 21 '13 at 16:18
  • 8
    The problem I have is that this answer is a half truth and miss-leads some people who are truly seeking to "clear" (I was). With as of now 48 up votes there is evidence that people without the time and diligence to read the other answers, may leave this page with incomplete information. Your answer is not wrong it requires an update stating that its not going to clear, its going to reset. :) – ktamlyn Feb 26 '13 at 17:27
  • 3
    Another thing to take into account is that reset() doesn't work with input hidden fields – MazarD Mar 28 '13 at 17:42
  • 2
    I agree with @ktamlyn I believe OP is trying to clear the form after submitting it via ajax. What's the point of resetting the form after submitting it? It would be really helpful if you update your answer to state that it is not going to clear and perhaps also show how to clear a form. – Stanley Apr 05 '13 at 02:55
  • @Jason McCreary your response is non-nonsensical. The whole point is that we are supporting people who could be misled by this "top answer". There are better answers already such as Brian Hoover below. The best we can do is down vote this answer and up vote the better ones. I have already done this. – ktamlyn Apr 05 '13 at 18:21
  • why not $("#myForm").trigger("reset");? – IlyaDoroshin Apr 29 '13 at 19:10
  • @Jason McCreary, it's just jquery way, i think – IlyaDoroshin Apr 30 '13 at 08:50
  • This doesn't work on checkboxes/radioButtons?? – James111 Jun 20 '15 at 04:24
  • `$('#myForm').trigger("reset");` Does work on checkboxes/radiobuttons! but `$('#myForm')[0].reset();` Doesn't – James111 Jun 20 '15 at 04:26
  • Can this be achieved on `div`s as well? – Shimmy Weitzhandler Jul 07 '15 at 02:48
163

To reset form (but not clear the form) just trigger reset event:

$('#form').trigger("reset");

To clear a form see other answers.

ktamlyn
  • 4,519
  • 2
  • 30
  • 41
IlyaDoroshin
  • 4,659
  • 4
  • 22
  • 26
  • 3
    This does not work in combination with client side validation. If the validation failed the reset does not clear invalid fields but resets them to the last input value. – Jürgen Bayer Jul 17 '13 at 18:49
  • 3
    @Jürgen Bayer nobody says about validation, it just resets the form to init values To clear invalid data you need to write your own method like: `$('#form input:invalid').val('')` – IlyaDoroshin Jul 18 '13 at 18:03
  • 3
    @IlyaDoroshin: I was just saying that it does not work when using client side validation. Could be an helpful information for others. other solutions in this thread that use val('') work even with client side validation. – Jürgen Bayer Jul 22 '13 at 05:53
  • This is neat, but the answer is incomplete. Setting the inputs to a value of "" is not the same as "reset()". See my answer as an option. – ktamlyn Feb 05 '14 at 16:07
85

Something similar to $("#formId").reset() will not clear form items that have had their defaults set to something other than "". One way this can happen is a previous form submission: once a form has been submitted reset() would "reset" form values to those previously submitted which will likely not be "".

One option to clear all forms on the page, is to call a function such as the following, executing it simply as clearForms():

function clearForms()
{
    $(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
    $(':checkbox, :radio').prop('checked', false);
}

If you want to reset a specific form, then modify the function as follows, and call it as clearForm($("#formId")):

function clearForm($form)
{
    $form.find(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
    $form.find(':checkbox, :radio').prop('checked', false);
}

When I originally came to this page I needed a solution that takes into account form defaults being changed and is still able to clear all input items.

Note that this will not clear placeholder text.

user664833
  • 18,397
  • 19
  • 91
  • 140
ktamlyn
  • 4,519
  • 2
  • 30
  • 41
  • 2
    Your code is for me the best solution. I just add the container as parameter to the function and a class for elements we won't reset. Final function looks like this : function clearForm($form) { $form.find(':input').not(':button, :submit, :reset, :hidden, .not-reset').val(''); } – Dayron Gallardo Feb 04 '14 at 08:19
  • 4
    @DayronGallardo Might also want to add `$(container_element).find(':checkbox, :radio').prop('checked', false);` – rybo111 Mar 16 '14 at 09:55
  • @DayronGallardo also remember to add `:checkbox, :radio` to the `.not` (I have suggested these edits). – rybo111 Mar 16 '14 at 11:08
  • 1
    You can just use the `$('#myForm').trigger("reset");` method to refresh/reset checkboxes and etc...! – James111 Jun 20 '15 at 04:26
  • 2
    James, you need to reread my post. – ktamlyn Jun 21 '15 at 17:34
  • I think this is the best. – nodeffect Sep 11 '15 at 02:08
  • @ktamlyn perfect solution, but how to stop form-select fields from clearing too? Rest all is perfect –  Oct 09 '22 at 07:37
22

Set the val to ""

function clear_form_elements(ele) {

        $(ele).find(':input').each(function() {
            switch(this.type) {
                case 'password':
                case 'select-multiple':
                case 'select-one':
                case 'text':
                case 'textarea':
                    $(this).val('');
                    break;
                case 'checkbox':
                case 'radio':
                    this.checked = false;
            }
        });

    }

<input onclick="clear_form_elements(this.form)" type="button" value="Clear All" />  
<input onclick="clear_form_elements('#example_1')" type="button" value="Clear Section 1" />
<input onclick="clear_form_elements('#example_2')" type="button" value="Clear Section 2" />
<input onclick="clear_form_elements('#example_3')" type="button" value="Clear Section 3" />

You could also try something like this:

  function clearForm(form) {

    // iterate over all of the inputs for the form

    // element that was passed in

    $(':input', form).each(function() {

      var type = this.type;

      var tag = this.tagName.toLowerCase(); // normalize case

      // it's ok to reset the value attr of text inputs,

      // password inputs, and textareas

      if (type == 'text' || type == 'password' || tag == 'textarea')

        this.value = "";

      // checkboxes and radios need to have their checked state cleared

      // but should *not* have their 'value' changed

      else if (type == 'checkbox' || type == 'radio')

        this.checked = false;

      // select elements need to have their 'selectedIndex' property set to -1

      // (this works for both single and multiple select elements)

      else if (tag == 'select')

        this.selectedIndex = -1;

    });

  };

More info here and here

Soatl
  • 10,224
  • 28
  • 95
  • 153
  • Add a $(this).change() at the end of the each-function to propagate the blank values to listeners. – Skynet Feb 11 '13 at 22:42
  • Method 1 is flawless and answers the question properly. Thanks for that – Onimusha Nov 02 '13 at 00:19
  • 1
    @Onimusha _Almost_ flawless. Remember to add [HTML5 input types](http://www.w3schools.com/html/html5_form_input_types.asp) to the first set of cases: `case 'color': case 'date': case 'datetime': case 'datetime-local': case 'email': case 'month': case 'number': case 'range': case 'search': case 'tel': case 'time': case 'url': case 'week':` – rybo111 Mar 16 '14 at 08:42
7
    <form id="form" method="post" action="action.php">
      <input type="text" class="removeLater" name="name" /> Username<br/>
      <input type="text" class="removeLater" name="pass" /> Password<br/>
      <input type="text" class="removeLater" name="pass2" /> Password again<br/>
    </form>
    <script>
$(function(){
    $("form").submit(function(e){
         //do anything you want
         //& remove values
         $(".removeLater").val('');
    }

});
</script>
genesis
  • 50,477
  • 20
  • 96
  • 125
5

You can simply use the reset button type.

<input type="text" />
<input type="reset" />

jsfiddle

Edit: Remember that, the reset button, reset the form for the original values, so, if the field has some value set on the field <input type="text" value="Name" /> after press reset the field will reset the value inserted by user and come back with the word "name" in this example.

Reference: http://api.jquery.com/reset-selector/

Eduardo M
  • 1,007
  • 11
  • 17
  • 2
    That resets the form. It does not clear it. if you set the value attribute on the textbox to `value='hello'` hitting reset all day will continue to display 'hello' – Doug Chamberlain Jun 20 '13 at 17:03
  • Yes, it's true. The `reset` button reset the form for the original values, I will update my answer. Thanks for the feedback. – Eduardo M Jun 20 '13 at 23:27
4

I use following solution:

1) Setup Jquery Validation Plugin

2) Then:

$('your form's selector').resetForm();
rusllonrails
  • 5,586
  • 3
  • 34
  • 27
3
function reset_form() {
 $('#ID_OF_FORM').each (function(){  
    this.reset();
 }); 
}
TheRealJAG
  • 1,978
  • 20
  • 16
3

the trigger idea was smart, however I wanted to do it the jQuery way, so here is a small function which will allow you to keep chaining.

$.fn.resetForm = function() {
    return this.each(function(){
        this.reset();
    });
}

Then just call it something like this

$('#divwithformin form').resetForm();

or

$('form').resetForm();

and of course you can still use it in the chain

$('form.register').resetForm().find('input[type="submit"]').attr('disabled','disabled')
Shaun Forsyth
  • 454
  • 4
  • 7
2

Would something like work?

JQuery Clear Form on close

Community
  • 1
  • 1
Brian Hoover
  • 7,861
  • 2
  • 28
  • 41
1

HTML

<form id="contactform"></form>

JavaScript

 var $contactform = $('#contactform')
    $($contactform).find("input[type=text] , textarea ").each(function(){
                $(this).val('');            
    });

Simple and short function to clear all fields

Tarun Gupta
  • 6,305
  • 2
  • 42
  • 39