Skip to content
Advertisement

How to make complete form in which background color of button changes when user starts typing in input field with javascript , html and css?

const btn = document.getElementById("btn");
const inputfield = document.getElementById("username");

inputfield.addEventListener("keyup", function(e) {
  const val = e.target.value;
  if (val === "") {
    btn.disabled = true;
    btn.style.backgroundColor = "grey";
  } else {
    btn.disabled = false;
    btn.style.backgroundColor = "orange";
  }
})
<div class="container">
  <input id="username" placeholder="Username" class="input" />
  <button disabled id="btn" type="button" class="button">Submit</button>
</div>

Now the issue is that it only works for one input and the associated button field it does not work for another pair of input field and button , so what changes should i make in the above javascript code in which it runs for as many as input field and button i want?

Please can anyone help me in this. Thank you

If you have full jquery code it’s also accepted.

Advertisement

Answer

My approach was to put the input and button in a div with a custom class. And just loop over every div, get the child inputs and buttons and just use your existing code for every div.

const btns = document.getElementsByClassName('inputButton');

for (let i = 0; i < btns.length; i++) {
  let input = btns[i].querySelector('input');
  let button = btns[i].querySelector('button');

  input.addEventListener("keyup", function(e) {
    const val = e.target.value;
    if (val === "") {
      button.disabled = true;
      button.style.backgroundColor = "grey";
    } else {
      button.disabled = false;
      button.style.backgroundColor = "orange";
    }
  });
}
<div class="container">
  <div class="inputButton">
    <input id="username" placeholder="Username" class="input" />
    <button disabled id="btn" type="button" class="button">Submit</button>
  </div>
  <div class="inputButton">
    <input id="username" placeholder="Username" class="input" />
    <button disabled id="btn" type="button" class="button">Submit</button>
  </div>
  <div class="inputButton">
    <input id="username" placeholder="Username" class="input" />
    <button disabled id="btn" type="button" class="button">Submit</button>
  </div>
</div>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement