Home > Mobile >  How do i change the backgroundcolor of a form element when clicked?
How do i change the backgroundcolor of a form element when clicked?

Time:09-28

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!

CodePudding user response:

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

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

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  • Related