Reputation: 2246
So, I'm working on a page with a contact form, and I want to have it check if field's are empty. I'm using this simple code below, but it only works for the first if. It only displays "I want to know who you are" when I click submit. It just doesn't even see the other if statements!
function validation() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var subject = document.getElementById("subject").value;
var message = document.getElementById("message").value;
if(name == null || name == "") {
document.getElementById("name-error").innerHTML = "I want to know who you are!";
return false;
}
if(email == null || email == "") {
document.getElementById("email-error").innerHTML = "Give me your email!";
return false;
}
if(subject == null || subject == "") {
document.getElementById("subject-error").innerHTML = "I need a subject!";
return false;
}
if(message == null || message == "") {
document.getElementById("message-error").innerHTML = "Don't forget your message!";
return false;
}
}
And this is the HTML:
<form name="contact" id="contact" action="./assets/send.php" method="post" id="form">
<label>Full name</label>
<input type="text" name="name" id="name"><span id="name-error"></span>
<label>Email</label>
<input type="text" name="email" id="email"><span id="email-error"></span>
<label>Subject</label>
<input type="text" name="subject" id="subject"><span id="subject-error"></span>
<label>Message</label>
<textarea name="message" id="message"></textarea><span id="message-error"></span>
<button onclick="return validation()" type="submit" name="send" id="send">Send</button>
</form>
Upvotes: 0
Views: 360
Reputation: 4372
Because you return false;
inside all if conditions, when one of them is met, it halts execution thereon. If you must use the return statement, put it right at the end, after all the if statements.
Upvotes: 0
Reputation: 49402
Because you are using return false;
inside the if()
, so the control returns after executing that if()
block.
if(name == null || name == "") {
document.getElementById("name-error").innerHTML = "I want to know who you are!";
return false; // control returns from the function here.
}
It would be better if you can keep a local variable inside the function and return it at the end of the function. Set it to true
initially , change it to false
inside if(){}
blocks and return it as the last statement of the function.
function validation() {
var isValid = true;
if(someThingWrong) {
// execute your logic here
isValid = false;
}
return isValid;
}
Upvotes: 2