I am currently working on creating a form and faced with the challenge of simplifying my code using a function. Specifically, I want to write JavaScript code that will check all input fields in the form to ensure they are filled. If any field is left empty, I'd like to change the style of that input box to display a red color. I have successfully implemented this for text inputs, but I'm wondering if there's a more efficient way to loop over all inputs and apply this functionality. Additionally, I'm open to suggestions on how to handle spans within the form elements, so any insight or examples would be greatly appreciated.
but.addEventListener("click", () => {
if (firstname.value == "" || lastname.value == "") {
firstname.style.backgroundColor = "rgba(200,0,0,.4)";
lastname.style.backgroundColor = "rgba(200,0,0,.4)";
span.style.display = "block";
span.innerHTML = "Please enter a valid Name";
}
if (age.value == ""){
span.style.display = "block";
age.style.backgroundColor = "rgba(200,0,0,.4)";
span.innerHTML = "Please enter your age";
} if (isNaN(age.value) == true ){
span.style.display = "block";
age.style.backgroundColor = "rgba(200,0,0,.4)";
span.innerHTML = "Please enter a valid Age";
} if (job.value == "") {
span.style.display = "block";
job.style.backgroundColor = "rgba(200,0,0,.4)";
span.innerHTML = "Please enter a role";
} if (email.value == "") {
span.style.display = "block";
email.style.backgroundColor = "rgba(200,0,0,.4)";
span.innerHTML = "Please enter an email";
} if (phone.value == "") {
span.style.display = "block";
phone.style.backgroundColor = "rgba(200,0,0,.4)";
span.innerHTML = "Please enter phone number";
}
})