I want to see if all the input fields are true, if not add a class "false" and a border around input-field. How do I check if all the inputs are true? Now I only get one border even if its two fields that are wrong. If lastname and age is wrong, I want to add a red border around the input.
function inputCount() {
var formPets = document.getElementsByTagName("input");
var firstName = document.getElementsByName("firstname")[0].value;
var lastName = document.getElementsByName("lastname")[0].value;
var age = document.getElementsByName("age")[0].value;
var email = document.getElementsByName("email")[0].value;
for (var i = 0; i < formPets.length; i++) {
if(firstName.value == "" || !isNaN(firstName) || firstName.length > 50)
{
alert("False");
var firstNameFalse = document.getElementById("firstname");
firstNameFalse.classList.add("false");
return false;
}
else if (lastName.value == "" || !isNaN(lastName) || lastName.length > 50){
alert("False");
var lastNameFalse = document.getElementById("lastname");
lastNameFalse.classList.add("false");
return false;
}
else if (age.value == "" || isNaN(age) || age.length > 0){
alert("False");
var ageFalse = document.getElementById("age");
ageFalse.classList.add("false");
return false;
}
else if (email.value == "" || !isNaN(email) || email.length > 50){
alert("False");
var emailFalse = document.getElementById("email");
emailFalse.classList.add("false");
return false;
}
else {
alert("OK");
}
}
}
#firstname.false {
border-color: red !important;
}
#lastname.false {
border-color: red !important;
}
#age.false {
border-color: red !important;
}
#email.false {
border-color: red !important;
}
<input type="text" name="firstname" id="firstname">Firstname<br>
<input type="text" name="lastname" id="lastname"> Lastname<br>
<input type="text" name="age" id="age"> Age<br>
<input type="text" name="email" id="email"> Email<br>
<button type="submit" onclick="inputCount()">Submit</button>
else if
toif
, remove allreturn
statements. If you want to returntrue
orfalse
, make that to a variable declared outside – Adarsh Mohan