'How to run JavaScript code when a form is being reset?

I know we can attach a handler to the form onsubmit... But how can we add a handler to the form reset event? (usually when clicking on <input type="reset">)

Or... Maybe there is no such event... So the question becomes on how to work-around that?

(right now, I want to run a handler after the reset event; but someday I might need to run before the reset event)



Solution 1:[1]

According to MDN, the <form> tag supports an onreset event.

Onreset fires before the actual resetting of the form; there doesn't appear to be any event for after resetting. I tested to see if the reset would fire an onchange event for the inputs whose values are reset, but it does not appear to.

A workaround for doing something after resetting might be to set a flag on reset, and then use the onblur event of the reset button (so after you reset, it would run the next time you click on something else). An alternate workaround, of course, is to trigger a setTimeout so that your script would run a short time after the reset. Either one is a bit of a hack, I'm afraid.

Solution 2:[2]

found an answer to this that worked for me so I thought I'd post it for anyone else who came across this.

Instead of <input type='reset'>, you can use a <button> element with a click handler that first calls the form.reset() method, then you can add whatever scripting you need to happen after the reset action.

Solution 3:[3]

You can use the "reset" event of the "form" element

<form action="form_action.php" onreset="return confirm('Do you really want to reset the form?');">

....

</form>

Solution 4:[4]

Have you tried

<form onreset="action()">

Seems to work for me for running the script before resetting the form. As for after ... I don't think it's supported, possibly a setTimeout would do the trick.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kapa
Solution 2 malificent
Solution 3 letronje
Solution 4 Richard Hoffman