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

171
Views
How do i change the backgroundcolor of a form element when clicked?

I've been trying to figure out how I can change the background color of a form element when it is clicked on.

Heres the code:

<form id="form">

 <input type="text" placeholder="text"/>
<input type="password" placeholder="more text" />

</form>

<script>

</script>

I'm trying to make it so the form element where it says "text" turns green when clicked, and the form element where it says "more text" turns red when clicked.

I've tried this, which didn't work:

<script>
let form = document.queryselector('input type="text"');

form.addEventListener('click', () => {

form.style.backgroundColor = 'green'

});
</script>

I'm very new to coding, so any help is very much appreciated! Thanks!

almost 4 years ago · Santiago Trujillo
3 answers
Answer question

0

The issue is with this line:

let form = document.queryselector('input type="text"');

First of all - the querySelector() method is camel cased - note the capital S. Secondly, your selector is not quite correct - you're looking for: input[type="text"]:

let form = document.querySelector('input[type="text"]');

form.addEventListener('click', () => {
  form.style.backgroundColor = 'green'
});
<form id="form">
  <input type="text" placeholder="text"/>
  <input type="password" placeholder="more text" />
</form>

Notice though that this doesn't change the background colour back once you focus out - you might be better off adding event listeners for the focusout, focusin and maybe blur events - but better still, you can use CSS:

form input[type="text"]:focus {
  background-color: green;
}
almost 4 years ago · Santiago Trujillo Report

0

you should write ('input[type="text"]');

<script>
    let form = document.querySelector('input[type="text"]');

    form.addEventListener("click", () => {
      form.style.backgroundColor = "green";
    });
</script>
almost 4 years ago · Santiago Trujillo Report

0

If you just want the input background to change color while it's focused. You can achieve this by using CSS selectors. No need for JS

input[type=text]:focus {
  background-color: red;
}

Or if you want the form background to change

form:focus-within {
  background-color:red;
}
almost 4 years ago · Santiago Trujillo 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!