461

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?

Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133
tbuehlmann
  • 9,032
  • 5
  • 27
  • 33
  • 2
    More detailed method to [**reset a form here**](http://jquery-howto.blogspot.com/2013/08/jquery-form-reset.html). – Uzbekjon Aug 30 '13 at 20:25
  • 1
    Check out the answer by Paolo Bergantino http://stackoverflow.com/questions/680241/blank-out-a-form-with-jquery – Wicked Coder Jun 15 '11 at 21:02

30 Answers30

697

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.

luvejo
  • 347
  • 2
  • 9
ngen
  • 8,816
  • 2
  • 18
  • 15
  • 3
    The first piece of code will set values of checkboxes to "" instead of just unchecking them. And it won't affect selects, because it is option tags that get selected. –  Jul 10 '13 at 08:59
  • 6
    to avoid removing checkbox values, I used the following, inspired by your answer: `$(':input').not(':button, :submit, :reset, :hidden').removeAttr('checked').removeAttr('selected').not(':checkbox, select').val('').removeAttr('value');`. It will remove default values (i.e. `value="something"`, but not for checkboxes or selects. – Jeppe Mariager-Lam Aug 22 '13 at 08:14
  • 19
    DO NOT USE THIS (option 1) if you have radios, checkboxes, or selects, you'll waste a lot of time finding a strange bug after their values disappear. The correct version, which leaves their values intact: `$(':input').not(':button, :submit, :reset, :hidden').removeAttr('checked').removeAttr('selected').not(':checkbox, :radio, select').val('');` (based on Jeppe Mariager-Lam's comment) – Konstantin Pereiaslov Oct 16 '13 at 10:32
  • 8
    Any reason to avoid the second option? – rineez Feb 19 '14 at 15:04
  • 3
    Second option resets the field value to its original value while option 1 blanks the form altogether. – JDuarteDJ Mar 24 '14 at 13:26
  • 1
    Important Note: because of :hidden selector, if the form is not visible, will not clear any fields. Example; if you are using a modal like bootstrap, you may want to clear the form after the modal closed. – Canser Yanbakan Jun 16 '14 at 21:57
  • @rineez nope. Instead, the second option imho should be always prevail over the first one considering that it is the standard(native) javascript function to reset a form. – DontVoteMeDown Jul 28 '14 at 18:33
  • Technically the second one resets the form to the initial state. It doesn't actually clear it if there were any initial values. – jeteon Jun 15 '15 at 00:42
  • 4
    Most of the time second option is what we need IMO. – Rk.. Nov 29 '15 at 06:00
  • 7
    your second solution is the actual answer – Manoochehr Dadashi Dec 12 '15 at 19:41
  • what if I have no form but all independent input fields in a container? basically each field is a filter and makes an ajax call. And I want to reset all fields. Would this work without a form by using container selector? – akd Feb 09 '17 at 22:43
  • or I should wrap the container with a form for only clearing fields purpose? – akd Feb 09 '17 at 22:46
  • Why is there a [0]on your second answer? Just want to be enlighten. @ngen – Wax May 05 '17 at 07:53
  • @Wax although be definition the ID selector should only return one DOM element, in jQuery instead it returns an array containing only one element. It is the jQuery's way to simplify the data processing without knowing the number of elements in an array. If you chain some jQuery methods after that array, it may correctly fetch the first element and do what should be done, like `val()`. But, `reset()` is a native DOM method and not jQuery method, so you fetch the first one and call it. Without `[0]`, `reset()` returns error. See this post: `questions/7183704/jquery-id-selector-id-returns-array` – WesternGun Dec 19 '17 at 11:51
  • $('#myform')[0].reset(); sets state to the previous. If I loaded form with empty fields, then it sets to emtpy fields. But if there is editing form with loaded data, then calling this - set fields to data which was before editing. – Dariux Jan 06 '18 at 15:47
  • Add `.text('').removeAttr('value')` to remove **textarea** & **input** default initial values. – stomy Jan 24 '19 at 17:08
534
$(".reset").click(function() {
    $(this).closest('form').find("input[type=text], textarea").val("");
});
ShaneBlake
  • 11,056
  • 2
  • 26
  • 43
  • 51
    Don't forget your `input[type=password]` fields. – SammyK Mar 22 '13 at 21:26
  • 66
    This answer covers the original question. Those wanting more than just text fields will obviously need to add code as needed... – ShaneBlake Jul 30 '13 at 22:19
  • 2
    also remember there will be more type of inputs other than type=password (like SammyK said) in HTML5: type=url, type=digits, type=email, etc [http://www.w3.org/TR/html5/forms.html#states-of-the-type-attribute](http://www.w3.org/TR/html5/forms.html#states-of-the-type-attribute) – Gabriel Sep 12 '13 at 22:56
  • 7
    A small tip: this selector won't select input elements that are relying on the implicit type=text, you must explicitly include the type=text on your markup. That may be obvious, but it wasn't to me, just now :-) – Elbin Oct 22 '13 at 14:34
  • 1
    Surprised this was the accepted answer. `$(this).closest('form')[0].reset()` is much simpler and covers all inputs/selects. – CaptSaltyJack Jun 11 '15 at 00:37
  • 2
    @CaptSaltyJack: That resets them to default values which isn't the same thing as clearing them... – ShaneBlake Jun 25 '15 at 20:23
  • 2
    Doesn't cover hidden fields. – MojoDK Jul 15 '15 at 06:31
  • Please keep in mind if setting values to an empty string using `element.val('')`, that any change bindings to the elements will not be triggered. You'll also need to add a `.trigger('change')` or `.change()` call as well. ex: `element.val('').trigger('change');` – Joshua Burns Sep 15 '17 at 16:42
  • This does not cover current available HTML5 fields (date, url, and so on). – Patrick Sep 19 '18 at 15:17
179

Any reason this shouldn't be used?

$("#form").trigger('reset');
user768680
  • 2,037
  • 1
  • 13
  • 6
66

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

Something like should work

$('yourdiv').find('form')[0].reset();
parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85
  • I just have the js code from my first post and want it to work on each page with several reset buttons in several forms. So it's just the selector that needs some contribution. – tbuehlmann Jun 15 '11 at 21:10
56

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.

Lukas Liesis
  • 24,652
  • 10
  • 111
  • 109
34

Simple but works like a charm.

$("#form").trigger('reset'); //jquery
document.getElementById("myform").reset(); //native JS
Djizeus
  • 4,161
  • 1
  • 24
  • 42
jroi_web
  • 1,992
  • 22
  • 23
33

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!

Tarmo Saluste
  • 585
  • 6
  • 18
  • As it says. It resets to the innital form value and not emptyes the values. But yes, If you have loaded form with default values, they won't be cleared. Probably a JS loop that goes trough all inputs and clears them – Tarmo Saluste Apr 25 '14 at 10:30
24
$('form[name="myform"]')[0].reset();
apen
  • 672
  • 4
  • 14
20

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('');
});
kumarharsh
  • 18,961
  • 8
  • 72
  • 100
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 1
    Tried that one first, it won't clear fields with default values. – tbuehlmann Jun 15 '11 at 21:08
  • There's another reason you often need JavaScript for this one. The form may not be a "form" at all. For example, your form is really just a collection of inputs for a Backbone.js/Ember.js/AngularJS app and the data will never be submitted as a traditional form to the server but needs to be processed strictly with JavaScript client side. In cases like this there's no form for reset to work on. – John Munsch Jul 06 '12 at 16:34
  • 3
    `.live()` is deprecated, and also it's slow/unnecessary. You could just use `.bind()` or `.on()`. – Kevin Beal Mar 20 '13 at 17:21
17

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

 $('#MyFormId')[0].reset();
Rashi Goyal
  • 933
  • 9
  • 15
16

I got easiest trick to reset form

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

or

$("#review-form").get().reset();
RavingDev
  • 2,817
  • 1
  • 17
  • 19
mumair
  • 2,768
  • 30
  • 39
15

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

BoCyrill
  • 1,219
  • 16
  • 17
11
$('#editPOIForm').each(function(){ 
    this.reset();
});

where editPOIForm is the id attribute of your form.

Jorge Y. C. Rodriguez
  • 3,394
  • 5
  • 38
  • 61
Knowledge Serve
  • 616
  • 7
  • 9
  • 2
    There will only ever be one `#editPOIForm` and so the `.each()` method makes no sense. Even if you added this id to multiple forms it would only ever return one of them. – Kevin Beal Mar 20 '13 at 17:19
  • 1
    The each() allows you to use this (instead of $(this)) to get at the underlying DOM object, and call reset(). Assuming you want to reset to default values, instead of clearing everything, this is a good solution. – Dave Jan 20 '14 at 17:24
  • @Dave Might as well just use `$('#editPOIForm').get(0).reset();` – Thomas Daugaard Jan 24 '14 at 16:04
  • 2
    @ThomasDaugaard: except that if you use get(0) or simply $('#editPOIForm')[0] you'll get a script error if $('#editPOIForm') matches no elements, whereas each() will fail without an error. So I suppose it depends on your priorities as far as error handling goes. – Dave Jan 27 '14 at 18:39
9

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

Carlos Alvarez
  • 124
  • 1
  • 3
9

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

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

BlackBeard
  • 10,246
  • 7
  • 52
  • 62
Mamun Sabuj
  • 189
  • 1
  • 2
  • 6
  • Just a little warning: If you have default values for the inputs, let's say server-rendered, then `form.reset();` will reset to those values, and not clear the inputs. – AntonJH Dec 11 '19 at 18:10
9

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.

Lewis
  • 2,718
  • 1
  • 11
  • 28
8

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.

Gaurang Joshi
  • 684
  • 16
  • 32
DeepCode
  • 358
  • 2
  • 9
7

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>
Matheno
  • 4,112
  • 6
  • 36
  • 53
6

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';
     }
 });
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
6

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('');
    }
    
Gregory Bowers
  • 786
  • 6
  • 6
6
$(document).ready(function() {
    $('#reset').click(function() {
    $('#compose_form').find("input[type=text] , textarea ").each(function() {
    $(this).val('');
   });
  });
});  
Khalid Butt
  • 71
  • 1
  • 3
5

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>
Monzur
  • 1,341
  • 14
  • 11
4
@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...

Sk8erPeter
  • 6,899
  • 9
  • 48
  • 67
L.W.C. Nirosh
  • 332
  • 1
  • 9
3

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('');
shivaP
  • 299
  • 1
  • 2
  • 12
2

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

$q(':input','#myform').not('#accountType').val('').removeAttr('checked').removeAttr('selected');
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 1
    you don't want to lose the values for the checkboxes en radiobuttons, but only uncheck them, this one is not a good solution – Frankey Apr 08 '13 at 08:29
2

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.

Rafael Kitover
  • 967
  • 10
  • 13
2

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

I've written a universal jQuery plugin:

/**
 * Resets any input field or form
 */
$.fn.uReset = function () {
    return this.filter('form, :input').each(function () {
        var input = $(this);
        
        // Reset the form.
        if (input.is('form')) {
            input[0].reset();
            return;
        }

        // Reset any form field.
        if (input.is(':radio, :checkbox')) {
            input.prop('checked', this.defaultChecked);
        } else if (input.is('select')) {
            input.find('option').each(function () {
                $(this).prop('selected', this.defaultSelected);
            });
        } else if (this.defaultValue) {
            input.val(this.defaultValue);
        } else {
            console.log('Cannot reset to default value');
        }
    });
};

$(function () {
    // Test jQuery plugin.
    $('button').click(function (e) {
        e.preventDefault();
        
        var button = $(this),
            inputType = button.val(),
            form = button.closest('form');
        
        if (inputType === 'form') {
            form.uReset()
        } else {
            $('input[type=' + inputType + '], ' + inputType, form).uReset();
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h3>Form</h3>
<form>
    <input type="text" value="default"/><br /><br />
    Ch 1 (default checked) <input type="checkbox" name="color" value="1" checked="checked" /><br />
    Ch 2 <input type="checkbox" name="color" value="2" /><br />
    Ch 3 (default checked) <input type="checkbox" name="color" value="3" checked="checked" /><br /><br />
    <select name="time"><br />
        <option value="15">15</option>
        <option selected="selected" value="30">30</option>
        <option value="45">45</option>
    </select><br /><br />
    R 1 <input type="radio" name="color" value="1" /><br />
    R 2 (default checked) <input type="radio" name="color" value="2" checked="checked" /><br />
    R 3 <input type="radio" name="color" value="3" /><br /><br />
    <textarea>Default text</textarea><br /><br />
    
    <p>Play with form values and then try to reset them</p>
    
    <button type="button" value="text">Reset text input</button>
    <button type="button" value="checkbox">Reset checkboxes</button>
    <button type="button" value="select">Reset select</button>
    <button type="button" value="radio">Reset radios</button>
    <button type="button" value="textarea">Reset textarea</button>
    <button type="button" value="form">Reset the Form</button>
</form>
Pete
  • 7,289
  • 10
  • 39
  • 63
Jekis
  • 4,274
  • 2
  • 36
  • 42
-2

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();
}
Sandip Jadhav
  • 7,377
  • 8
  • 44
  • 76
-5
$('form').submit(function() {

    var el = $(this);

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

    return false;

});
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98