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:
- Getting started with jquery: interesting to have a look at it
- Clearing form data: how could you erase all the data in a form (this is not about reseting the form, this is actually about clearing the form)
Español
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.
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()06/09/2011 at 8:13 pm Permalink
Thanks Pau, it works
15/10/2011 at 5:44 am Permalink
$(‘#myform’).get(0).reset();