James
James

Reputation: 818

Form submit after preventDefault

I'm trying to validate a form before it is submitted. I've tried a couple of methods but I cant get the form to submit after preventDefault. This is the code I have at the moment:

$('#formquote').submit(function(e){
        e.preventDefault(); 
        console.log('here');
        validating = true;
        var tval = valText('input[name=contactname]');
        var pval = valPhone('input[name=telephone]');
        var eval = valEmail('input[name=email]');

        console.log(tval);
        console.log(pval);
        console.log(eval);

        if(tval && pval && eval){
            $("#formquote").unbind('submit');
            $("#formquote").submit();
        }
    });

The console logs you can see output as expected ('here', true, true, true respectively) At the moment the form submits on the second time you press the button. I've also tried the following suggestions to no avail:

-> $("#formquote").unbind('submit').submit(); //same result
-> $("#formquote").submit(); //by itself, infinite loop
-> $("#formquote")[0].submit(); //non function error
-> $('#formquote').unbind('submit', preventDefault); //'preventDefault' not defined

Any help would be appreciated

Upvotes: 1

Views: 7188

Answers (2)

pusle
pusle

Reputation: 1513

I guess the accepted answer is the best way of doing this, but if, for some reason, you need to use preventDefault() first and then submit the form, this works for me:

$('#formquote').on('submit', function (e) {
  e.preventDefault();
  // Do validation stuff..
  // Then submit the form
  $(this).submit();
}

Upvotes: -2

Anthony Grist
Anthony Grist

Reputation: 38345

Instead of always preventing the form from submitting, doing your validation and submitting again if it passes, why don't you just prevent the submission when the validation fails? Something like this:

$('#formquote').submit(function (e) {
    validating = true;
    var tval = valText('input[name=contactname]');
    var pval = valPhone('input[name=telephone]');
    var eval = valEmail('input[name=email]');

    if (!(tval && pval && eval)) {
        e.preventDefault();
    }
});

Upvotes: 4

Related Questions