54

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?

Brian David Berman
  • 7,514
  • 26
  • 77
  • 144
  • 1
    You could bind to the reset event of the form, however that happens just before the input values get reset. There isn't an event that runs right after the inputs get reset. – Kevin B Apr 25 '12 at 16:03
  • If you must wait until the inputs are reset, do a setInterval within the reset event that clears itself when it detects that the input's values have been reset, and then runs your code. – Kevin B Apr 25 '12 at 16:08
  • @OP you find anything useful? – iambriansreed Apr 25 '12 at 16:29
  • 1
    @Kevin_B, why `setInterval` instead of `setTimeout`? – Doin Sep 30 '15 at 20:16

10 Answers10

147

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() { /* ... */ });
});
Ben
  • 5,117
  • 2
  • 27
  • 26
  • is ommitting the second parameter to setTimeout universally supported? w3schools and mozilla both list it as a required param. seems to work fine in all my browsers, but i'm not sure about older IE – Kip Apr 18 '14 at 18:37
  • 1
    @Kip Yeah it works just fine in older IE. Haven't tested IE6 but I'm not too worried about that. Works just fine in strict mode too. However adding the zero might add some clarity to your code. – Ben Apr 19 '14 at 07:01
  • It wouldn't function properly in any modern browser for me without setting the timeout. Not sure on the order of execution but guessing that the reset event is when the form starts resetting, not when the reset is done. – Kurtis Cochrane Aug 05 '16 at 15:31
  • I was missing `setTimeout` part. Trying to figure out why things go wrong when I press the reset button, for a few minutes now. If it wasn't for this answer, I could've wasted another hour onto this. Thanks. – Monday Fatigue Apr 28 '17 at 10:50
  • The reason you have to use `setTimeout()` here is because the function is a **handler**, not a callback. I'd be curious how to do this without `setTimeout()`. The only way I can think of is to use `preventDefault()` and just handle resetting the form yourself. – Scribblemacher Aug 31 '17 at 19:39
63

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/

iambriansreed
  • 21,935
  • 6
  • 63
  • 79
  • Not sure who down-voted you and why, but I up-voted you and accepted your answer. Thanks. – Brian David Berman Apr 25 '12 at 17:12
  • 2
    Binding to the event rather than when the button clicked is much more reliable! – Pez Cuckow Nov 25 '14 at 19:23
  • 1
    Yes the answer below (by Benjammin') should be marked as the preferred solution. A form reset can be caused by a `` or even a JavaScript. Bind to a click event on the submit button is too indirect. I guess that is what the downvotes are for. – Blaise Feb 17 '16 at 16:10
  • I have to agree with @PezCuckow and recommend Benjamin Fleming's answer. – Sam_Butler Mar 24 '18 at 03:55
4

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/

Mike Mertsock
  • 11,825
  • 7
  • 42
  • 75
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
}
Blip
  • 3,061
  • 5
  • 22
  • 50
IgniteCoders
  • 4,834
  • 3
  • 44
  • 62
0

try

$('your-form').bind('reset', function() {
  alert('hi');
});
Dominic
  • 62,658
  • 20
  • 139
  • 163
  • [This link](http://forum.jquery.com/topic/trapping-the-form-reset-event) should provide background and some documentation on how and why this works, and also, why there isn't more in the jQuery docs concerning it. – Paul Bruno Apr 25 '12 at 16:02
  • This executes before the form is reset. – Brian David Berman Apr 25 '12 at 16:04
  • try binding to a change event inside the event then, as the next change will be the reset action – Dominic Apr 25 '12 at 16:09
  • This is great but didn't the OP ask for the event to be attached to the reset button click? – iambriansreed Apr 25 '12 at 16:28
  • 2
    yes he did but its better to bind to the reset event, like its better to bind to submit than a submit button. You go to the route of the event not bind on a presentation member. Thanks for the downvote. – Dominic Apr 25 '12 at 16:31
  • You noticed the OP's comment, right: "This executes before the form is reset." – iambriansreed Apr 25 '12 at 16:34
0

Here an example using the onreset event similar to how you normally use the onsubmit event of the form element to catch clicking on a submit button. The onsubmit example is added for clarification.

In your script:

function submitForm(form){
    var xhr = new XMLHttpRequest(),
        data = new FormData(form);

    xhr.open("POST", url, true);
    xhr.onload = function(event) {
        switch (event.target.status){
            case 200:
                onSuccess(event);
                break;
            default:
                onError(event);
        }
    };
    xhr.send(data);
    return false;
}

function resetForm(form){
    var elements = form.elements;
    // set some initial values to those form elements
    return false;
}

In your html:

<form onsubmit="return submitForm(this);" onreset="return resetForm(this);">
    <button type="submit">Save</button>
    <button type="reset">Reset</button>
</form>
Wilt
  • 41,477
  • 12
  • 152
  • 203
0

Reset the display contents when clicking the reset button.

$('.custom-file-input').on('change', function(){
    const $label = $(this).next('.custom-file-label');
    const fileName = $(this).val().split('\\').pop(); 
    $label.data('default', $label.html());
    $label.addClass('selected').html(fileName);
});

$('form').on('reset', function(){
    $('.custom-file-input').each(function(){
        const $label = $(this).next('.custom-file-label');
        $label.html($label.data('default'));
    });
});
Logue
  • 29
  • 4
0

I ended up using a promise to allow me to chain dom changes together. That way I can ensure the form is reset first, before resetting other dom stuff which needs to change based on input in the form, which includes resetting the form too. I don't necessarily expect the form reset to fail, so I don't use the reject function:

const form = document.getElementById("saveForm");
const resetBtn = form.querySelector("button[type=reset]");
resetBtn.addEventListener("click", function overrideReset(e) {
    e.preventDefault();
    return new Promise((resolve, reject) => resolve(form.reset())).then(() => {
        //run code here.
    });
});
stepquick
  • 398
  • 1
  • 3
  • 14
-1

would this help

  $("input[type='reset']").on("click", function(){
    alert("the form has been reset");
  });

link to jsfiddle: http://jsfiddle.net/sdkTz/1/

DG3
  • 5,070
  • 17
  • 49
  • 61
-5

Add a click event to the reset button, and have it look like this:

function(e) {
    setTimeout(function() {
        // your actual code here
    },1);
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592