ninho
ninho

Reputation: 31

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!

Upvotes: 1

Views: 99

Answers (4)

DannyXCII
DannyXCII

Reputation: 928

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;
}

Upvotes: 2

Ehsan
Ehsan

Reputation: 137

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

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

    form.addEventListener("click", () => {
      form.style.backgroundColor = "green";
    });
</script>

Upvotes: 2

Khab
Khab

Reputation: 104

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;
}

Upvotes: 2

Dereemii
Dereemii

Reputation: 71

I would recommend add and Id or a css class into your input tag then you can use querySelector --> https://www.w3schools.com/jsref/met_document_queryselector.asp

Upvotes: 1

Related Questions