This is the Script:
This is the page: https://intro-component-sign-up-five.vercel.app/
const spanContainer = document.querySelectorAll(".form-container span");
const spanImg = document.querySelectorAll(".errorIcon")
const submitBtn = document.querySelector(".submit");
const inputAll = document.querySelectorAll("form input");
const input = document.querySelector("input");
let formData = {}; // objeto para armazenar os dados do formulário
input.addEventListener("input", function(event) {
formData[input.name] = input.value; // atualiza o valor do objeto com o valor atual do input
});
//input.addEventListener("input", errorForm);
function handleClick(event) {
inputAll.forEach((input) => {
if(input.value === "") {
event.preventDefault();
errorForm();
}
})
}
function errorForm() {
spanContainer.forEach((span) => {
if(span.innerText === ""){
span.classList.add("errorMessage");
}
if(span.classList.contains("errorMessage")) {
span.classList.add("error");
}
spanImg.forEach((img) => {
if(img.classList.contains("errorIcon")) {
img.classList.add("selected");
}
})
inputAll.forEach((input) => {
if(input.classList.contains("submit") === false && input.value === "") {
input.classList.add("error");
input.nextElementSibling.nextElementSibling.classList.add("error");
} else {
input.classList.remove("error");
input.nextElementSibling.classList.remove("errorMessage");
input.nextElementSibling.classList.remove("selected");
input.nextElementSibling.nextElementSibling.classList.remove("error");
}
})
})
}
submitBtn.addEventListener("click", handleClick);
Things work fine, just the way I want it to work, but I keep getting this console error:
Uncaught TypeError: Cannot read properties of null (reading 'classList')
at script.js:41:51
at NodeList.forEach (<anonymous>)
at script.js:35:12
at NodeList.forEach (<anonymous>)
at errorForm (script.js:23:17)
at script.js:16:7
at NodeList.forEach (<anonymous>)
at HTMLInputElement.handleClick (script.js:13:12)
I tried to fix it by removing the second “nextElementSibling”, but when I do it the page doesn’t work the way I want anymore. The errorMessage is not removed once I submit again after I fulfill the respective input.