简体   繁体   中英

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

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();
    }
});

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM