jQuery/Javascript function to clear all the fields of a form

JavascriptJquery

Javascript Problem Overview


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!

Javascript Solutions


Solution 1 - Javascript

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 https://stackoverflow.com/questions/680241/resetting-a-multi-stage-form-with-jquery.

Solution 2 - Javascript

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

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

To clear a form see other answers.

Solution 3 - Javascript

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.

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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/

Solution 7 - Javascript

I use following solution:

  1. Setup Jquery Validation Plugin

  2. Then:

    $('your form's selector').resetForm();

Solution 8 - Javascript

function reset_form() {
 $('#ID_OF_FORM').each (function(){  
    this.reset();
 }); 
}

Solution 9 - Javascript

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

Solution 10 - Javascript

Solution 11 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDiegoP.View Question on Stackoverflow
Solution 1 - JavascriptJason McCrearyView Answer on Stackoverflow
Solution 2 - JavascriptIlyaDoroshinView Answer on Stackoverflow
Solution 3 - JavascriptktamlynView Answer on Stackoverflow
Solution 4 - JavascriptSoatlView Answer on Stackoverflow
Solution 5 - JavascriptgenesisView Answer on Stackoverflow
Solution 6 - JavascriptEduardo MView Answer on Stackoverflow
Solution 7 - JavascriptrusllonrailsView Answer on Stackoverflow
Solution 8 - JavascriptTheRealJAGView Answer on Stackoverflow
Solution 9 - JavascriptShaun ForsythView Answer on Stackoverflow
Solution 10 - JavascriptBrian HooverView Answer on Stackoverflow
Solution 11 - JavascriptTarun GuptaView Answer on Stackoverflow