I am unable to figure where is the issue in my JavaScript code. I want show and hide the error message based on whether the field value is empty or not.
if (info == "" && hrContacts == "") {
document.getElementById("hr_contacts_error").style.display = "block";
document.getElementById("info_error").style.display = "block";
return false;
} else if (hrContacts == "") {
document.getElementById("hr_contacts_error").style.display = "block";
return false;
} else if (hrContacts != "") {
document.getElementById("hr_contacts_error").style.display = "none";
} else if (info == "") {
document.getElementById("info_error").style.display = "block";
return false;
} else if (info != "") {
document.getElementById("info_error").style.display = "none";
} else if (info != "" && hrContacts != "") {
form submit
}
3
Answers
I would simply do :
no need for all those if/else
Also try to rely on native html validation as much as you can, like maxlength, min, max attributes and so on
You can simplify this a lot.
true
.return false
to prevent form submit.You could reduce some code duplication like this:
You did not tell us how you call the validation.
Here is how you SHOULD call it
NOTE: Simply adding
required
to the form fields can replace the validation of empty fields completely