5

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)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Denilson Sá Maia
  • 47,466
  • 33
  • 109
  • 111

4 Answers4

6

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.

kapa
  • 77,694
  • 21
  • 158
  • 175
Jacob Mattison
  • 50,258
  • 9
  • 107
  • 126
  • Accepting your answer because you cited a good reference. (even though I was kinda expecting a W3C or Mozilla Developer Center link) – Denilson Sá Maia Sep 10 '10 at 13:24
  • Huh... I should have tested before... Using `onreset` will run the script BEFORE resetting, and not after. – Denilson Sá Maia Sep 10 '10 at 13:42
  • Instead of registering a `blur` event handler, in your `reset` event handler, you can call `setTimeout` with a timeout value of `0` which has the effect of scheduling the function (the one you specify as the first argument to `setTimeout`) to run after current script "frame" processes. All your form controls will have been reset by then, which is why you'd want to have your code run then. – Armen Michaeli Apr 22 '18 at 12:25
4

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.

malificent
  • 1,441
  • 14
  • 18
2

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>
letronje
  • 9,002
  • 9
  • 45
  • 53
1

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.

Richard Hoffman
  • 729
  • 3
  • 10