
We often need specific input types to improve the user experience. One common need is a number-only input field.
While HTML5 offers a basic <input type="number">, it lacks customization options. This is where Numeric Input comes in.
This lightweight JavaScript library provides customizable numeric input fields where users can set minimum and maximum values, initial values, and decimal places.
In addition, Numerical Input validates and formats user input in real time. It prevents the entry of invalid characters and restricts the entry to numbers, a minus sign (for negative values), and a decimal separator.
How to use it:
1. Download the library and load the core script ‘numericinput.js’ in the HTML document.
<script src="./js/numericinput.js" defer></script>
2. Create regular input fields with the name “numeric-input” and customize them using the following attributes:
- minval: Sets the minimum allowed value (e.g., minval=”-10.2″).
- maxval: Defines the maximum allowed value (e.g., maxval=”10.2″).
- decimal: Specifies the number of decimal places (e.g., decimal=”2″).
- initialval: Sets the initial value of the input field (e.g., initialval=”10″).
<input type="text" name="numeric-input" minval="-100" maxval="100" initialval="0" decimal="2">
How it works:
Numerical Input sets up event listeners for focus, blur, paste, and input events on all elements with the name “numeric-input”.
The focus event selects all text in the field. The blur event formats the input and enforces min/max limits. The paste event blocks non-numeric characters. The input event removes invalid characters and formats the value.
A regex pattern filters out non-numeric input. It also handles decimal formatting based on the “decimal” attribute.
The library uses modern JavaScript features for concise logic. It checks for undefined values and uses optional chaining for better error handling.







