I am new to javascript, so I apologize if this is all totally wrong, but I'm trying to validate a form right now, and I have the simple functions for testing. I want the function validateForm() to return all three of the functions checkName(), checkEmail, and checkMessage(). The way I have the validateForm() function, it only runs the checkName() function. Any ideas?
function checkName(){
var name=document.forms["contactForm"]["Name"].value;
if(name==null || name==""){
$("input#name").css("border-color", "#ff0000");
$("input#name").attr("placeholder","Your name is required");
return false;
}
else {
$("input#name").css("border-color", "#00a8ff");
$("input#name").attr("placeholder","");
return true;
}
}
function checkEmail(){
var email=document.forms["contactForm"]["Email"].value;
if(email==null || email==""){
$("input#email").css("border-color", "#ff0000");
$("input#email").attr("placeholder","Your email is required");
return false;
}
else {
$("input#email").css("border-color", "#00a8ff");
$("input#email").attr("placeholder","");
return true;
}
}
function checkMessage(){
var message=document.forms["contactForm"]["Message"].value;
if(message==null || message==""){
$("textarea#message").css("border-color", "#ff0000");
$("textarea#message").attr("placeholder","Your message is required");
return false;
}
else {
$("textarea#message").css("border-color", "#00a8ff");
$("textarea#message").attr("placeholder","");
return true;
}
}
function validateForm(){
return checkName() && checkEmail() && checkMessage();
}
&&immedately returns false as soon as one of the operands (from left to right) is false. Dmitry's answer is best, and you should use it, but rename variablesa,b, andcto something meaningful. Beware of hacks, though. It turs out that the replacing all instances of&&with&in the return statement will also work for you, but the reasons why are very technical and the approach is not recommended. Understanding it, though, may give you insight into short-circuiting which is very valuable.