简体   繁体   中英

How do I return false and stop an email being sent if one or more if statements is false Javascript?

I'm quite new to JavaScript and I'm having an issue with a contact form.

I have 2 if statements and I return false at the end of the second one, but when I execute this, with both fields empty, its happy, and my error msgs pop up, and the email doesn't send. but if I only enter information in the second input field, it thinks the form is filled out, even with the first field empty.

How do I stop the email from sending if either one of the if statements is false?

My code

function checkForm(){
    if   (streetAddress.value == "") {  
            addressErrorMsg.style.display="block";
    }

    if   (fullname.value == "") {  
            nameErrorMsg.style.display="block";

       return false;
    }
    else{                       
       return true;
    }
}
function checkForm(){
    var validate = true;
    if   (streetAddress.value == "") {  
            addressErrorMsg.style.display="block";
            validate = false;
    }

    if   (fullname.value == "") {  
            nameErrorMsg.style.display="block";
            validate = false;

    }
    return validate;
}

Keep track of the state and have one return statement at the end.

function checkForm(){
    var isValid = true;
    if   (streetAddress.value == "") {  
            addressErrorMsg.style.display="block";
            isValid = false;
    }

    if   (fullname.value == "") {  
            nameErrorMsg.style.display="block";

       isValid = false;
    }
    return isValid;
}

And looking at your code, I am hoping you have

var addressErrorMsg = document.getElementById("SomeId"); 

above your code and you are not just using the id to reference the element.

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