After clicking an html reset button,
<input type="reset" />
I would like to execute some code. How can I do this and ensure that the form was reset prior to doing so?
JQuery doesn't have a reset() method, but native JavaScript does. So, we convert the jQuery element to a JavaScript object. JavaScript reset(): The reset() method resets the values of all elements in a form (same as clicking the Reset button).
reset() method restores a form element's default values. This method does the same thing as clicking the form's <input type="reset"> control. If a form control (such as a reset button) has a name or id of reset it will mask the form's reset method. It does not reset other attributes in the input, such as disabled .
The onreset event occurs when a form is reset.
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() { /* ... */ }); });
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With