Search code examples
javascriptinnertext

Change the color of innerText according to the input value using JavaScript


Below is a sample code for changing color on InnerText by a value in an input text.

The output looks like this. The color doesn't change

enter image description here

function validate() {
  var msg;
  var result;
  if (document.myForm.userPass.value.length > 5) {
    msg = "good";
    result = msg.fontcolor("green");
  } else {
    msg = "poor";
    result = msg.fontcolor("red");
  }
  document.getElementById('mylocation').innerText = result;
}
<form name="myForm">
  <input type="password" value="" name="userPass" onkeyup="validate()"> Strength:
  <span id="mylocation">no strength</span>
</form>

The answers given here is not the one I needed.


Solution

  • Since the font tag is not used by HTML5, the old fontcolor method will not work in browsers.

    So I tried the below code.

    function validate() {
      var msg;
    
      if (document.myForm.userPass.value.length > 5) {
        document.getElementById('mylocation').style.color = "green";
        msg = "good";
      } else {
        document.getElementById('mylocation').style.color = "red";
        msg = "poor";
      }
      document.getElementById('mylocation').innerText = msg;
    }
    <form name="myForm">
      <input type="password" value="" name="userPass" onkeyup="validate()"> Strength:
      <span id="mylocation">no strength</span>
    </form>
    <hr/>