It seems like there might be a better way to approach your code, one that aligns more closely with your requirements. One possible solution involves listening for the keyup
event and checking if the input has any content. This approach can be customized to suit your specific needs.
I've also made some adjustments by moving the loop inside the submit button click handler to prevent adding multiple identical handlers to the button.
const submitButton = document.getElementById("submit")
const inputField = document.querySelectorAll(".input")
submitButton.addEventListener("click", function(e) {
inputField.forEach(function(item) {
e.preventDefault();
if (item.value == '') {
item.classList.add("red");
item.nextElementSibling.classList.add("red");
} else {
item.classList.add("green")
item.nextElementSibling.classList.remove("green");
}
})
})
inputField.forEach(function (item) {
item.addEventListener('keyup', function(e) {
const theInput = e.target;
if (theInput.value) {
theInput.classList.remove('red');
theInput.classList.add('green');
}
});
});
.red {
border: red 2px solid;
}
.green {
border: green 2px solid;
}
<label for="myfield">My Field:</label>
<input class="input" id="myfield" name="myfield" />
<br/>
<label for="myotherfield">My Other Field:</label>
<input class="input" id="myotherfield" name="myotherfield" />
<button id="submit">Submit</button>
An alternative option is to rely on native validation without using JavaScript-- this means you have less control over when and how validation styles are applied, but it also reduces the amount of JavaScript needed:
const submitButton = document.getElementById("submit")
submitButton.addEventListener("click", function(e) {
e.preventDefault();
});
.input:invalid {
border: red 2px solid;
}
.input:valid {
border: green 2px solid;
}
<label for="myfield">My Field:</label>
<input class="input" id="myfield" name="myfield" required/>
<br/>
<label for="myotherfield">My Other Field:</label>
<input class="input" id="myotherfield" name="myotherfield" required />
<button id="submit">Submit</button>
In case you opt for the first method, remember to provide sufficient feedback for screen readers and assistive technologies to comprehend the form's status. For instance, if there are no validation or validation-state attributes on the input fields and only color-coded borders to indicate validity, users relying on screen readers may not be aware of it. Additionally, individuals with red/green color blindness may struggle to differentiate between the colors.