I am unable to figure where is the issue on the javascript, I want show and hide the error message based on the field values is empty or not,
Please find the my javascript code,
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
}
>Solution :
You can simplify this a lot.
- First, set the initial state, assume there are no errors, and hide all messages.
- Check every individual field, and if there’s an input error, display the message, and set the error tracking boolean to
true. - If at the end, there are any errors,
return falseto prevent form submit. - Actually submit the form, if there’s no errors.
let hasError = false;
document.getElementById("hr_contacts_error").style.display = "none";
document.getElementById("info_error").style.display = "none";
if (hrContacts == "") {
document.getElementById("hr_contacts_error").style.display = "block";
hasError = true;
}
if (info == "") {
document.getElementById("info_error").style.display = "block";
hasError = true;
}
if (hasError) {
return false;
}
// form submit
You could reduce some code duplication like this:
let hasError = false;
// Loop over all fields with their error message ID.
[
[hrContacts, 'hr_contacts_error'],
[info, 'info_error']
].forEach(([value, errorId]) => {
const isEmpty = value == '';
document.getElementById(errorId).style.display = isEmpty ? 'block' : 'none';
hasError = hasError || isEmpty;
});
if (hasError) {
return false;
}
// form submit