How to change user input color in javascript once they have typed in their answer

2065 views javascript
5

I am trying to change color of user input based on a range of numbers they input. (ie over 100 is red, 75 to 100 is yellow, 50 to 75 is black, 25 to 50 is yellow and anything less is red)

Here is a snippet of my code that I have tried so far...

in HTML:

< input type="text" class="celltext" id="flexion" onkeyup="colorChange()"/>

in JS:

function colorChange() {

    var patientROM = document.getElementById("flexion");

    if (patientROM > 100) {
       patientROM.style.color="#FF0000";
    } else if (patientROM <= 100 && patientROM > 75) {
        PatientROM.style.color="#FFFF00";
    } else if (patientROM <= 75 && patientROM > 50) {
        patientROM.style.color="#330000";
    } else if (patientROM <= 50 && patientROM > 25) {
        patientROM.style.color="#FFFF00";
    } else if (patientROM <= 25) {
        patientROM.style.color="#FF0000";
    } else {
        alert("Invalid Input, please try again");
    }
}

When I type in my input it goes straight to the alert("Invalid Input, please try again");

Is there a way to do it with the onchange element as well? I have tried both onkeyup and onchange

answered question

var patientROM = document.getElementById("flexion"); should be var patientROM = document.getElementById("flexion").value;

1 Answer

6

you can pass the input into the function call instead of using document to find by id

function colorChange(el) {
  const value = parseInt(el.value);
  console.log(value)

  if (value > 100) {
    el.style.color="#FF0000";
  } else if (value > 75) {
    el.style.color="#00FF00";
  } else if (value > 50) {
    el.style.color="#0000FF";
  } else if (value > 25) {
    el.style.color="#ffff00";
  } else if (value >= 0) {
    el.style.color="#00ffff";
  } else {
    console.log("Invalid Input, please try again");
  }
}
<input type="text" class="celltext" id="flexion" onKeyUp="colorChange(this)"/>

posted this

Have an answer?

JD

Please login first before posting an answer.