Reputation: 884
I was wondering if there was any way of "undoing" the preventDefault() method on submit. I have this code that does the trick, but I want to know if there is a more efficient way of doing it.
var $form = $('form');
var canSubmit = false;
$form.data('working', false);
$form.submit(function(e){
if (form.validations.form($form)) {
if (!$form.data('working')) {
$form.data('working', true);
if (canSubmit) {
// make the post here
} else {
e.preventDefault();
$.get(BASE+'file.txt', function(response){
$form.data('canSubmit', true);
$form.submit();
});
}
}
} else {
$form.data('working', false);
e.preventDefault();
return false;
}
});
This is because I have to read and write a file after the validations are done and only after that make the post to the page. The post can't be done by ajax.
Thanks
Upvotes: 2
Views: 5109
Reputation: 93571
You can't undo the e.preventDefault()
as you are dealing with a later instance of e
by the time you submit.
return false
does the same as e.preventDefault()
and e.stopPropagation()
, so you can simplify your code a little though by simply returning your flag.
var $form = $('form');
var canSubmit = false;
$form.data('working', false);
$form.submit(function(e){
if (form.validations.form($form)) {
if (!$form.data('working')) {
$form.data('working', true);
if (!canSubmit) {
e.preventDefault();
$.get(BASE+'file.txt', function(response){
canSubmit = true;
$form.submit(); // trigger recursive call
});
}
}
} else {
$form.data('working', false);
}
return canSubmit;
});
Upvotes: 2