Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute code after html form reset with jquery?

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?

like image 822
Brian David Berman Avatar asked Apr 25 '12 15:04

Brian David Berman


People also ask

How we can reset form in JQuery?

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).

What does reset () do in JavaScript?

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 .

Which event is executed when reset button is clicked?

The onreset event occurs when a form is reset.


2 Answers

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() { /* ... */ }); }); 
like image 138
Ben Avatar answered Sep 22 '22 08:09

Ben


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/

like image 31
iambriansreed Avatar answered Sep 20 '22 08:09

iambriansreed