How to reset a form in jQuery

Reseting the form to it’s initial values is one of those things you often do once and once again.

Doing this task with jQuery is really easy:

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

The thing is, that the code above iterates through each element of the form, and calls to the DOM “reset” javascript method. In fact, the “reset” function does not exist in jQuery.

It would be much more simple to do something like $(“#FormID”).reset(). Fortunately creating that function in jQuery only will take a minute of programming:

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

Using the code above, reseting a form would be just one call (as desired):

$("#FormID").reset();

May be using the name “reset” is too generic to be applied to any object (it will only work on forms), but I think it has a lot of sense to name it ‘reset’. But anyway, feel free to call it “resetForm” if you feel more comfortable.

Interesting links:

Trackback URL

, , , ,

97 Comments on "How to reset a form in jQuery"

  1. Ralph Moran
    23/07/2009 at 8:33 pm Permalink

    Saludos,

    Muy buen tip!

    Seria bueno mejorarlo para que solo funcion para forms o elementos DOM que acepten reset.

    Suerte, hasta luego.

  2. Ben
    01/04/2010 at 7:38 am Permalink

    A better reset function would be:

    jquery.fn.reset = function(fn) {
    return fn ? this.bind("reset", fn) : this.trigger("reset");
    };

    This would allow you to attach a reset function using:
    $("#FormID").reset(function(){ /* do something */ })

    In the same way as you would attach a submit function:
    $("#FormID").submit(function(){ /* do something */ })

    in addition to being able to trigger a reset by calling:
    $("#FormID").reset()

  3. Budi
    06/09/2011 at 8:13 pm Permalink

    Thanks Pau, it works ;)

  4. kevin
    15/10/2011 at 5:44 am Permalink

    $(‘#myform’).get(0).reset();

Trackbacks

  1. [...] Resetear un formulario con jQuery [...]

Hi Stranger, leave a comment:

ALLOWED XHTML TAGS:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Subscribe to Comments