I wrote the code below and I'm trying to change the input field background color the moment I type something. I have 4 input fields. If I click submit in the first time and any field is empty, the color of this field will change to red, but I need to change the color to green the moment I fill this empty field.
const submitButton = document.getElementById("submit")
const inputField = document.querySelectorAll(".input")
let requiredField = document.querySelectorAll(".requiredField")
inputField.forEach(function (item){
submitButton.addEventListener("click", function (){
if(item.value == '') {
item.classList.add("red");
item.nextElementSibling.classList.add("red");
}
else{
item.classList.add("green")
item.nextElementSibling.classList.remove("green");
}
})
})
Try this:
inputField.forEach(field => {
field.addEventListener("input", () => {
field.classList.add("green");
});
});
If you want only one field to be green at a time:
inputField.forEach(field => {
field.addEventListener("input", () => {
inputField.forEach(input => {
input.classList.remove("green");
});
field.classList.add("green");
});
});
You don't actually need any JavaScript for this. Add the required attribute on the inputs and then style them accordingly with css.
<input type="text" required>
<input type="text" required>
<input type="text" required>
<input type="text" required>
input:valid {
background-color: green;
}
input:invalid:required {
background-color: red;
}
try this for a quick fix:
const submitButton = document.getElementById("submit")
const inputField = document.querySelectorAll(".input")
inputField.forEach(field => {
field.addEventListener("input", () => {
inputField.forEach(input => {
input.classList.remove("green");
input.classList.remove("red");
});
if (field.value !== "") {
field.classList.add("green");
} else {
field.classList.add("red");
}
});
});