0

I'm having a hard time with the submit handler... Why does the following still submit form when form fields left empty?

$("form").submit(function() {

$(".required").each(function() { //check each instance with class of 'required'.
if ($(this).val() == "") { //if field left blank,
return false; //halt / prevent form submission.
}
//else ..
return true; //all is ok, proceed.
});

});

2 Answers 2

3

Because your return true; will execute for any non-empty field, thus preventing the code from checking all fields. In addition, you are only returning out of the inner function, and not the submit handler. You should rewrite to something like this:

$("form").submit(function() {

    isValid = true;

    $(".required").each(function() { //check each instance with class of 'required'.
        if ($(this).val() == "") { //if field left blank,
            isValid = false;
        }    
    });

    return isValid; //all is ok, proceed.

});
Sign up to request clarification or add additional context in comments.

Comments

0

Quick answer: I think it's because your return false is nested in an $.each function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.