Home > OS >  Auto Change Font Color Red & Green
Auto Change Font Color Red & Green

Time:03-03

I Want To Change Multiple Textbox Color Automatic Using Class.

<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 Font color is Green

Text Box 2 : If I Type -2 (negative value) Then Font color is Red

Text Box 3 : If I Type 0 Then Font color is Black

Note: I Don't Wont Unique ID, Please Help

CodePudding user response:

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.

CodePudding user response:

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" />

CodePudding user response:

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"  />

    <input type="text"  />

    <input type="text"  />
    <script src="src/index.js"></script>
  </body>
</html>

  • Related