Tracking value of number inputs using CSS — Amit Merchant — A blog on PHP, JavaScript, and more

0
13

There are scenarios where you might want to track the value of an input field, especially the number of inputs, and change the theming of the input field based on the value.

For instance, you might want to change the color of the input field to red if the value is less than 10 and green if the value is greater than 10.

At first, you may want to reach for JavaScript to do this. But, there’s a way to do this using CSS only. Let’s see how.

Making input field trackable by CSS

To make a number input field trackable by CSS, we first need to specify the range of the input field using the min and max attributes.

<input type="number" min="1" max="10">

As you can see, I’ve specified the min and max attributes to 1 and 10 respectively. This means that the input field will only accept values ​​between 1 and 10.

Using CSS to track the value

Now, we can use CSS to track the value of the input field.

To do so, we can use the :in-range and :out-of-range pseudo-classes to track the value of the input field.

To update the styling of the input field when the value is in range, we can use the :in-range pseudo-class.

input[type="number"]:in-range 
    background-color: green;

This will update the background color of the input field to green when the value is in range.

Similarly, we can use the :out-of-range pseudo-class to update the styling of the input field when the value is out of range.

input[type="number"]:out-of-range 
    background-color: red;

This will update the background color of the input field to red when the value is out of range.

Here’s a working demo of the above.

See the Pen
Tracking number input using CSS
by Amit Merchant (@amit_merchant) on CodePen.

Try changing the value of the input field and you’ll see the background color of the input field changes accordingly.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here