Search code examples
javascripthtmlcssinputonmouseover

How to change the background color of input tag only for specific values


I want to set background-color: #F5B7B1 property of an input tag, but only for values ​​less than 1 and more than a 1000. Why does this code not working?

    function f() {
    var input=this.getElementById("number_input").value;
    if (input<1||input>1000)this.getElementById("number_input").style.backgroundColor=#F5B7B1;}
<form class="w3-container w3-card-4 w3-pale-green central">
    <h2>Desired Input</h2>

    <p><input class="w3-input w3-border" onmouseover="f()" type="number" id="number_input" placeholder="Enter a number between 1 and 1000!"></p>
</form>


Solution

  • this inside function refers to the window object which does not have getElementById()

    You should pass this to the function so that you can refer that inside the function. I also think using oninput event is more meaningful here.

    Also note that the colour coded value is string, you have to wrap that with quotes ("#F5B7B1" or '#F5B7B1').

    function f(el) {
      console.clear();
      console.log(this.constructor.name) //Window
      var input=el.value;
      if (input<1 || input>1000)el.style.backgroundColor="#F5B7B1";
      else{
        el.style.backgroundColor="lightgray";
      }
    }
    <form class="w3-container w3-card-4 w3-pale-green central">
      <h2>Desired Input</h2>
    
      <p><input class="w3-input w3-border" oninput="f(this)" type="number" id="number_input" placeholder="Enter a number between 1 and 1000!"></p>
    </form>