-1

I want to change multiple textbox colors automatically using the class property.

<input type="text" Class="ChangeColor" />

<input type="text" Class="ChangeColor" />

<input type="text" Class="ChangeColor" />

Text Box 1 : If I Type 25 (Positive value), then the font color is green

Text Box 2 : If I Type -2 (negative value), then the font color is red

Text Box 3 : If I Type 0, then the font color is black

Note: I do not want to use Unique ID's.

Craws
  • 576
  • 4
  • 30
Harshil
  • 5
  • 4

3 Answers3

0

You will need to use JavaScript to get the value from the input.

With the value from the input, you can add a logic to change the color to green if the value is greater than 25.

Craws
  • 576
  • 4
  • 30
0

Here you go, uses CSS classes - added Not A Number (NaN) as a bonus

const classes = ['nan', 'negative', 'zero', 'positive'];
document.querySelectorAll('input.ChangeColor')
.forEach(input => input.addEventListener('input', function(e) {
  this.classList.remove(...classes);
  if (this.value.length) {
    this.classList.add(classes[(Math.sign(+this.value) + 2) || 0]);
  }
}));
.ChangeColor.zero {
  color: black;
}

.ChangeColor.negative {
  color: red;
}

.ChangeColor.positive {
  color: green;
}

.ChangeColor.nan {
  border-color: red;
}
<input type="text" Class="ChangeColor" />
<input type="text" Class="ChangeColor" />
<input type="text" Class="ChangeColor" />
Bravo
  • 6,022
  • 1
  • 10
  • 15
-1

const inputs = document.getElementsByClassName("ChangeColor");

Array.prototype.forEach.call(inputs, (item) => {
  item.addEventListener("input", function (e) {
    if (e.target.value > 0) {
      e.target.style.color = "green";
    } else if (e.target.value < 0) {
      e.target.style.color = "red";
    } else {
      e.target.style.color = "black";
    }
  });
});
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="app"></div>
    <input type="text" class="ChangeColor" />

    <input type="text" class="ChangeColor" />

    <input type="text" class="ChangeColor" />
    <script src="src/index.js"></script>
  </body>
</html>
Šimon Slabý
  • 533
  • 1
  • 4
  • 18