How to execute code after html form reset with jquery?
Solution 1:
I don't particularly like the idea of binding the reset event to the reset button instead of the form. A form can be reset by other means and in those cases your event will not trigger.
Instead, bind the function to the reset event but place it within an instantaneous setTimeout. It will ensure the form is actually reset prior to calling the function.
$('form').on('reset', function(e)
{
setTimeout(function() { /* ... */ });
});
Solution 2:
Using a setTimeout as Ben does here is best: https://stackoverflow.com/a/21641295/144665
$("input[type='text']").val('Hello Everybody!');
$("input[type='reset']").closest('form').on('reset', function(event) {
// executes before the form has been reset
console.log('before reset: ' + $("input[type='text']").val());
setTimeout(function() {
// executes after the form has been reset
console.log('after reset: ' + $("input[type='text']").val());
}, 1);
});
You might want to narrow that form selector down to the specific form involved, maybe with an id.
Fiddle Proof: http://jsfiddle.net/iambriansreed/Zh5cd/
Solution 3:
Update: use preventDefault
instead of return false
.
$('input[type="reset"]').click(function(evt) {
// Prevent the reset button from firing the form's reset event again
evt.preventDefault();
$(this).closest('form').get(0).reset();
// At this point your form's inputs should have their values reset
});
http://jsfiddle.net/EYqrX/1/
Solution 4:
The suggestion is that instead of using <input type='Reset'>
use <input type = "button">
in this way you do not have to stop the default behaviour of the reset
button. You simply have to add the onclick
attribute to the button and in the function you could call the form's reset method where ever you wish and control the behaviour as you wish. The following code illustrates that
HTML:
<input type="button" value="Limpiar" onclick="resetForm(this);"/>
JavaScript:
function resetForm(element) {
//Do what you need before reset the form
element.form.reset(); //Reset manually the form
//Do what you need after reset the form
}