[jquery] Clear form fields with jQuery

I want to clear all input and textarea fields in a form. It works like the following when using an input button with the reset class:

$(".reset").bind("click", function() {
  $("input[type=text], textarea").val("");
});

This will clear all fields on the page, not just the ones from the form. How would my selector look like for just the form the actual reset button lives in?

This question is related to jquery html forms

The answer is


By using a combination of JQuery's .trigger() and native Javascripts's .reset() all form elements can be reset to blank state.

$(".reset").click(function(){
    $("#<form_id>").trigger("reset");
});

Replace <form_id> with id of form to reset.


$('form').submit(function() {

var el = $(this);

$('<button type="reset" style="display:none; "></button>')
    .appendTo(el)
    .click()
    .remove()
;

return false;

});


Simple but works like a charm.

$("#form").trigger('reset'); //jquery
document.getElementById("myform").reset(); //native JS

Use this Code Where you want to Call Normal Reset Function by jQuery

setTimeout("reset_form()",2000);

And Write this Function Out Site jQuery on Document Ready

<script>
function reset_form()
{
    var fm=document.getElementById('form1');
    fm.reset();
}
</script>

Let us say if you want to clear the fields and except accountType,in the mean time dropdown box will be reset to particular value,i.e 'All'.Remaining fields should be reset to empty i.e text box.This approach will be used for clearing particular fields as our requirement.

 $(':input').not('#accountType').each( function() {

    if(this.type=='text' || this.type=='textarea'){
             this.value = '';
       }
    else if(this.type=='radio' || this.type=='checkbox'){
         this.checked=false;
      }
         else if(this.type=='select-one' || this.type=='select-multiple'){
              this.value ='All';
     }
 });

Why does it need to be done with any JavaScript at all?

<form>
    <!-- snip -->
    <input type="reset" value="Reset"/>
</form>

http://www.w3.org/TR/html5/the-input-element.html#attr-input-type-keywords


Tried that one first, it won't clear fields with default values.

Here's a way to do it with jQuery, then:

$('.reset').on('click', function() {
    $(this).closest('form').find('input[type=text], textarea').val('');
});

the code I see here and on related SO questions seems incomplete.

Resetting a form means setting the original values from the HTML, so I put this together for a little project I was doing based on the above code:

            $(':input', this)
                .not(':button, :submit, :reset, :hidden')
                .each(function(i,e) {
                    $(e).val($(e).attr('value') || '')
                        .prop('checked',  false)
                        .prop('selected', false)
                })

            $('option[selected]', this).prop('selected', true)
            $('input[checked]',   this).prop('checked',  true)
            $('textarea',         this).each(function(i,e) { $(e).val($(e).html()) })

Please let me know if I'm missing anything or anything can be improved.


if you use selectors and make values to empty values, it is not resetting the form, it's making all fields empty. Reset is to make form as it was before any edit actions from user after the load of form from server side. If there is an input with name "username" and that username was prefilled from server side, most of solutions on this page will delete that value from input, not reset it to the value how it was before user's changes. If you need to reset the form, use this:

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

if you need not to reset the form, but fill all inputs with some value, for example empty value, then you can use most of the solutions from other comments.


If you want to empty all input boxes irrespective of its type then it's a minute step by

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

With Javascript you can simply do it with this syntax getElementById("your-form-id").reset();

you can also use jquery by calling the reset function this way $('#your-form-id')[0].reset();

Remember not to forget [0]. You will get the following error if

TypeError: $(...).reset is not a function

JQuery also provides an event you can use

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

I tried and it works.

Note: Its important to notice that these methods only reset your form to their initial value set by the server on page load. This means if your input was set on the value 'set value' before you did a random change, the field will be reset to that same value after reset method is called.

Hope it helps


Some of you were complaining that radios and such are cleared of default "checked" status... All you have to do is add the :radio, :checkbox selectors to the .not and the problem is solved.

If you can't get all the other reset functions to work, this one will.

  • Adapted from ngen's answer

    function form_reset(formID){
        $(':input','#'+formID)
        .not(':button',':submit',':reset',':hidden',':radio',':checkbox')
        .val('');
    }
    

I've written a universal jQuery plugin:

_x000D_
_x000D_
/**_x000D_
 * Resets any input field or form_x000D_
 */_x000D_
$.fn.uReset = function () {_x000D_
    return this.filter('form, :input').each(function () {_x000D_
        var input = $(this);_x000D_
        _x000D_
        // Reset the form._x000D_
        if (input.is('form')) {_x000D_
            input[0].reset();_x000D_
            return;_x000D_
        }_x000D_
_x000D_
        // Reset any form field._x000D_
        if (input.is(':radio, :checkbox')) {_x000D_
            input.prop('checked', this.defaultChecked);_x000D_
        } else if (input.is('select')) {_x000D_
            input.find('option').each(function () {_x000D_
                $(this).prop('selected', this.defaultSelected);_x000D_
            });_x000D_
        } else if (this.defaultValue) {_x000D_
            input.val(this.defaultValue);_x000D_
        } else {_x000D_
            console.log('Cannot reset to default value');_x000D_
        }_x000D_
    });_x000D_
};_x000D_
_x000D_
$(function () {_x000D_
    // Test jQuery plugin._x000D_
    $('button').click(function (e) {_x000D_
        e.preventDefault();_x000D_
        _x000D_
        var button = $(this),_x000D_
            inputType = button.val(),_x000D_
            form = button.closest('form');_x000D_
        _x000D_
        if (inputType === 'form') {_x000D_
            form.uReset()_x000D_
        } else {_x000D_
            $('input[type=' + inputType + '], ' + inputType, form).uReset();_x000D_
        }_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<h3>Form</h3>_x000D_
<form>_x000D_
    <input type="text" value="default"/><br /><br />_x000D_
    Ch 1 (default checked) <input type="checkbox" name="color" value="1" checked="checked" /><br />_x000D_
    Ch 2 <input type="checkbox" name="color" value="2" /><br />_x000D_
    Ch 3 (default checked) <input type="checkbox" name="color" value="3" checked="checked" /><br /><br />_x000D_
    <select name="time"><br />_x000D_
        <option value="15">15</option>_x000D_
        <option selected="selected" value="30">30</option>_x000D_
        <option value="45">45</option>_x000D_
    </select><br /><br />_x000D_
    R 1 <input type="radio" name="color" value="1" /><br />_x000D_
    R 2 (default checked) <input type="radio" name="color" value="2" checked="checked" /><br />_x000D_
    R 3 <input type="radio" name="color" value="3" /><br /><br />_x000D_
    <textarea>Default text</textarea><br /><br />_x000D_
    _x000D_
    <p>Play with form values and then try to reset them</p>_x000D_
    _x000D_
    <button type="button" value="text">Reset text input</button>_x000D_
    <button type="button" value="checkbox">Reset checkboxes</button>_x000D_
    <button type="button" value="select">Reset select</button>_x000D_
    <button type="button" value="radio">Reset radios</button>_x000D_
    <button type="button" value="textarea">Reset textarea</button>_x000D_
    <button type="button" value="form">Reset the Form</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_


None of the above works on a simple case when the page includes a call to web user control that involves IHttpHandler request processing (captcha). After sending the requsrt (for image processing) the code below does not clear the fields on the form (before sending the HttpHandler request ) everythings works correctly.

<input type="reset"  value="ClearAllFields" onclick="ClearContact()" />

 <script type="text/javascript">
       function ClearContact() {
           ("form :text").val("");
       }
    </script>

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

where editPOIForm is the id attribute of your form.


If someone is still reading this thread, here is the simplest solution using not jQuery, but plain JavaScript. If your input fields are inside a form, there is a simple JavaScript reset command:

document.getElementById("myform").reset();

More about it here: http://www.w3schools.com/jsref/met_form_reset.asp

Cheers!


The following code clear all the form and it's fields will be empty. If you want to clear only a particular form if the page is having more than one form, please mention the id or class of the form

$("body").find('form').find('input,  textarea').val('');

I got easiest trick to reset form

jQuery("#review-form")[0].reset();

or

$("#review-form").get().reset();

Any reason this shouldn't be used?

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

Why you dont use document.getElementById("myId").reset(); ? this is the simple and pretty


Add hidden reset button as follows

<input id="resetBtn" type="reset" value="reset" style="display:none" />
// Call reset buttons click event
// Similar to ClearInputs('resetBtn');
function ClearInputs(btnSelector) {
     var btn = $("#" + btnSelector);
     btn.click();
}

This won't handle cases where form input fields have non empty default values.

Something like should work

$('yourdiv').find('form')[0].reset();

$(document).ready(function() {
    $('#reset').click(function() {
    $('#compose_form').find("input[type=text] , textarea ").each(function() {
    $(this).val('');
   });
  });
});  

For jQuery 1.6+:

$(':input','#myform')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .prop('checked', false)
  .prop('selected', false);

For jQuery < 1.6:

$(':input','#myform')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .removeAttr('checked')
  .removeAttr('selected');

Please see this post: Resetting a multi-stage form with jQuery

Or

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

As jQuery suggests:

To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.


Most easy and best solution is-
$("#form")[0].reset();

Don't use here -
$(this)[0].reset();


$('form[name="myform"]')[0].reset();

If i want to clear all the fields except accountType..Use the following

$q(':input','#myform').not('#accountType').val('').removeAttr('checked').removeAttr('selected');

I use this :

$(".reset").click(function() {
  $('input[type=text]').each(function(){
     $(this).val('');
  });
});

And here is my button:

<a href="#" class="reset">
  <i class="fa fa-close"></i>
     Reset
</a>

Tested and verified code:

  $( document ).ready(function() {
    $('#messageForm').submit(function(e){
       e.preventDefault();
    });
    $('#send').click(function(e){
      $("#messageForm")[0].reset();
    });
  });

Javascript must be included in $(document).ready and it must be with your logic.


@using (Ajax.BeginForm("Create", "AcceptanceQualityDefect", new AjaxOptions()
{
    OnSuccess = "ClearInput",
    HttpMethod = "Post",
    UpdateTargetId = "defect-list",
    InsertionMode = InsertionMode.Replace
}, new { @id = "frmID" })) 
  1. frmID is the identification of the form
  2. OnSuccess of the operation we call the JavaScript function with the name "ClearInput"

    <script type="text/javascript">
        function ClearInput() {
            //call action for render create view
            $("#frmID").get(0).reset();
        }
    </script>
    
  3. if you do both of these right, then you will not be able to stop it from working...


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"