Leo Messi
Leo Messi

Reputation: 6166

Input changes border based on its value

There is an input which accepts numerical values. If the value is greater than 10 it should change its border color to red and also show a tooltip with a text "value is too big".

This is the input:

<input className="my-input" type="number" />

I don't know how to connect the input value to css, I've made it turn the border red when the cursor is inside the input (:focus):

input:focus {
  border: 1px solid red;
  outline: none;
}

But how can it be done to change the border color when the input values is greater than 10? and also to show a tooltip when its happening

Upvotes: 0

Views: 868

Answers (2)

albert
albert

Reputation: 474

You could probably try below which works on most modern browsers.

input:focus:invalid {
  border: 1px solid red;
  outline: none;
}
<input type="number" max="10" />

Upvotes: 1

Mehdi Diabi
Mehdi Diabi

Reputation: 61

This is where JavaScript comes to the rescue, what you should do is the following:

  • Create a css class to indicate the error style for the input.
  • listen to value change of the input and add the error css class when value is superior than 10.

It's very simple:

    function isValid(value) {
      return parseInt(value) <= 10;
    }

    // "input-error" is the css class for error
    const cssErrorClass = "input-error"
    function oninputchange(ev) {
      if(!isValid(ev.target.value)) {
        ev.target.classList.add(cssErrorClass)
      }
      else if(ev.target.classList.contains(cssErrorClass)) {
        ev.target.classList.remove(cssErrorClass);
      }
    }
    document.getElementById("my-input").onkeyup = oninputchange;
    document.getElementById("my-input").onchange = oninputchange;
.input-error {
  border: 1px solid red !important;
  outline: none;
}
    <input id="my-input" type="number" />

Upvotes: 1

Related Questions