Brieuc
Brieuc

Reputation: 4114

Jquery, prevent redirecting, validating then submit the form

I need to validate a form and display the errors if there are. (that part of the script is working)

If there is no error i would like to submit the form (no ajax, just keep redirecting as before with the Posted data).

My actual code does not redirect at all. i don't see any other way than using .submit() for posting the data.

if i'm not mistaken window.location.href would not post the data.

 $('#contact-form').submit(function(e) {

    e.preventDefault();

    var count_error = 0;

    // Validating ...

    if(count_error == 0){
        $('#contact-form').submit(); //Redirecting to the form action with posted data
    }

});

Upvotes: 0

Views: 1612

Answers (2)

Brieuc
Brieuc

Reputation: 4114

Solution given by Adam Merrifield

remove e.preventDefault();from the beginning. Then change your if statement to if(count_error !== 0){ e.preventDefault(); //display errors } Basically instead of stoping the submission of the form and then restarting it if there are no errors. Only stop it if there are errors. –

Upvotes: 0

APAD1
APAD1

Reputation: 13666

$("#contact-form").submit(function(e) {
    var count_error = 0;

    // Validating ...

    if (count_error == 0) {
        return;
    }
    e.preventDefault();
});

Upvotes: 3

Related Questions