I have an additional function to execute before I submit the form. This isn't doing the trick.
$('form').submit( function(event) {
var formId = $(this).attr('id');
mySpecialFunction(formId);
event.preventDefault();
setTimeout( function () {
$(this).submit();
}, 300);
});
This isn't working obviously.
The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmit property in the HTML <form> element.
Returning "false" from the submit handler will prevent the form from submitting.
Here is the way that works for me: const form = $("#formId"); form. submit(() => { //some other functions you need to proceed before submit setTimeout(() => {}, 1200); return true; }); Now it will wait 1200 ms before submitting the form.
You need to fire the event on the form element itself, not on a jQuery selection. (In fact, you weren't even selecting the form element – inside setTimeout
, this
is the global object.)
Cache a reference to the form (this
) and call its submit
method:
$('form').submit( function(event) {
var formId = this.id,
form = this;
mySpecialFunction(formId);
event.preventDefault();
setTimeout( function () {
form.submit();
}, 300);
});
Note that I have also replaced your inefficient $(this).attr('id')
call with this.id
. Note also that you have to call the DOM form element's submit method, not the jQuery method, so that the jQuery event handler is not triggered, which would cause an infinite (and totally ineffectual) loop.
$('form').submit( function(event) {
var formId = this.id,
$this = $(this);
mySpecialFunction(formId);
event.preventDefault();
$this.unbind("submit");
setTimeout( $.proxy( $.fn.submit, $this ), 300);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With