简体   繁体   中英

jQuery Stop submitting form by checking error variable

I have a simple form with some form fields. Some of them are required some are not. The required field are required by adding the class 'required'.

When I submit I check the #contact-form fields and on the basis of there I give the empty field error classes and submit the form yes or no.

Adding the error classes to the fields is not a problem, but checking the "error" variable is. Because I don't know where I can check the error variable.

This is my jQuery code:

$('#contact-form').submit(function (event) {
    var errors = false;
    $(this).find('.required').each(function () {
        if ($(this).val().length < 1) {
            $(this).addClass('error');
            errors = true;
        }
    });
    if (errors == true) {
        event.preventDefault();
    }
});

JsFiddle

The following code should do what you want, just give your contact form submit button the id of #contact-form-button .

$('#contact-form-button').click(function(e) {  // using click function
                                               // on contact form submit button
    e.preventDefault();  // stop form from submitting right away

    var error = false;

    $(this).find('.required').each(function () {
        if ($(this).val().length < 1) {
            $(this).addClass('error');
            error = true;
        }
    });

    if (!error) {                     // if not any errors
        $('#contact-form').submit();  // you submit form
    }

});
$('#contact-form').submit(function (event) {
    var errors = false;
    $(this).find('.required').each(function () {
        if ($(this).val().length < 1) {
            $(this).addClass('error');
            errors = true;
        }
    });
    if (errors == true) {
        event.preventDefault();
        return false;
    }
    return true;
})

if validation cross successfully then it return true for submit the form

I found out that my code just works. The reason I thought it was not working, is because I was still using PHP handling my real website where I made 1 field required and in my jQuery not. This made the confusion.

So the following code works:

$('#contact-form').submit(function (event) {
    var errors = false;
    $(this).find('.required').each(function () {
        if ($(this).val().length < 1) {
            $(this).addClass('error');
            errors = true;
        }
    });
    if (errors == true) {
        event.preventDefault();
    }
});

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