I am trying to add my error message and icon for all inputs that are invalid, however, it only works for the first input. What am i doing wrong? This is not my full solution just a piece of code that is not working, I intend to solve the rest on my own.
I tried using input.value
to but that did not work either.
const input = document.querySelectorAll("input");
input.forEach((input) => {
input.addEventListener("invalid", getErrorMsg);
input.addEventListener("focus", removeErrorMsg);
})
function getErrorMsg(e) {
const errorIcon = document.querySelector(".error-icon");
const errorTxt = document.querySelector(".error-txt");
errorIcon.classList.add("active");
errorTxt.classList.add("active");
};
function removeErrorMsg(e) {
const errorIcon = document.querySelector(".error-icon");
const errorTxt = document.querySelector(".error-txt");
errorIcon.classList.remove("active");
errorTxt.classList.remove("active");
}
.inputDiv {
position: relative;
border: 1px solid transparent;
}
.error-icon {
display: none;
position: absolute;
top: 18px;
right: 30px;
}
.error-txt {
display: none;
color: var(--CLR-RED);
font-style: italic;
font-size: 0.8em;
font-weight: var(--FW-BOLD);
position: absolute;
bottom: -10px;
right: 0;
}
.error-icon.active,
.error-txt.active {
display: block;
}
<form class="formContainer">
<div class="inputDiv">
<input class="input" type="text" id="firstName" name="firstName" placeholder="First Name" required>
<img class="error-icon" src="images/icon-error.svg" alt="">
<p class="error-txt">First Name cannot be empty</p>
</div>
<div class="inputDiv">
<input class="input" type="text" id="lastName" name="lastName" placeholder="Last Name" required>
<img class="error-icon" src="images/icon-error.svg" alt="">
<p class="error-txt">Last Name cannot be empty</p>
</div>
<div class="inputDiv">
<input class="input" type="email" id="email" name="email" placeholder="Email Address" required>
<img class="error-icon" src="images/icon-error.svg" alt="">
<p class="error-txt">Looks like this is not an email</p>
</div>
<div class="inputDiv">
<input class="input" type="password" id="password" name="password" placeholder="Password" required>
<img class="error-icon" src="images/icon-error.svg" alt="">
<p class="error-txt">Password cannot be empty</p>
</div>
<button type="submit" class="freeTrialBtn">
Claim your free trial
</button>
</form>