How can I run a piece of code as soon as a form has been reset?
The reset event fires before the form fields get reset to their default values. So, for example:
$('form').on('reset', function(e) {
    $('input').val('a value that should be set after the form has been reset');
});
This won't work. (Demo)
As the reset event fires before the browser handles the default form reset behavior, the code above simply sets the input's value right before the reset event's default action takes place, restoring the input's value to its default value. This makes sense, as so I'd be able to call e.preventDefault() to cancel the form resetting.
My use case requires executing code as soon as the form has been reset. In simple cases, a setTimeout would suffice:
$('form').on('reset', function(e) {
    setTimeout(function() {
        $('input').val('yay it works now');
    }, 0);
});
This works, as the setTimeout will execute sometime in the future, after the reset has finished bubbling and the browser has handled its default action.
However, this loses synchronicity. As soon as I have to programmatically reset the form and manipulate it from another place, everything goes down the drain.
$('form').on('reset', function(e) {
    setTimeout(function() {
        $('input').val("reset'd value");
    }, 0);
});
//somewhere in another module..
$('form').trigger('reset');
$('input').val('value after resetting the form');
(Demo)
Of course, everything is supposed to happen synchronously, but only my reset event handling is pushed to asynchronously run in the future, thus it ends up running after all the current synchronous pile of code has executed, when it was supposed to run right after the form has been reset.
Solutions I've thought about:
- Use yet another setTimeoutto run after thesetTimeout. This is overly ugly and I refuse to jump into asetTimeouthell.
- Implement a wrapper for resetting the form which either takes a callback function or returns a promise object. This seems a bit overkill though.
If only an afterreset event existed.. Well, did I overlook something or are the solutions above my only options?
I've came across these questions while searching:
But their titles are (imho) a bit misleading, seeing as those are actually very distant from my problem.
 
     
    