Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

303
Views
How to change the input field background color right after I type something?

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");     
    }    
  })
})
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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");
  });
});
about 4 years ago · Juan Pablo Isaza Report

0

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;
}
about 4 years ago · Juan Pablo Isaza Report

0

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");
    }
  });
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!