Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute code as soon as form has been reset [duplicate]

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 setTimeout to run after the setTimeout. This is overly ugly and I refuse to jump into a setTimeout hell.
  • 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:

  • Call a function after form reset
  • Perform Javascript action after reset button handles click

But their titles are (imho) a bit misleading, seeing as those are actually very distant from my problem.

like image 418
Fabrício Matté Avatar asked Nov 13 '22 01:11

Fabrício Matté


1 Answers

In your case, I think you just simply assign a default value to your textbox. As the form is reset, the browser will automatically reset it to the default value.

<form>
    <input value="Abc" type="text"/>
    <input type="reset" />
</form>

Check demo.

like image 153
Khanh TO Avatar answered Nov 14 '22 22:11

Khanh TO