Allowing only numeric digits in an input field can be useful in many web development projects, especially when working with forms and data input. HTML and JavaScript can be used to achieve this task easily.
Here is the HTML code to create a simple input field:
<input type="text" id="numericInput">
And here is the JavaScript code to restrict the input to only numeric digits:
document.getElementById("numericInput").addEventListener("keypress", function(event) {
var key = event.keyCode;
// Only allow numbers to be entered
if (key < 48 || key > 57) {
event.preventDefault();
}
});
DEMO
See the Pen Untitled by Puneet Sharma (@webdevpuneet) on CodePen.
The above code uses the “keypress” event listener to listen for any key presses in the input field. The “event.keyCode” property is used to determine the ASCII code of the key that was pressed. The code then checks if the key code is outside the range of numbers (48 to 57), and if so, it uses the “event.preventDefault()” method to prevent the character from being entered into the input field.
You can also use the “input” event instead of “keypress” to capture changes to the input field, including those made with the mouse or by pasting text. In this case, you would need to check the value of the input field after each change and remove any non-numeric characters.
document.getElementById("numericInput").addEventListener("input", function() {
this.value = this.value.replace(/[^\d]/g, "");
});
You can also use an inline script to achieve the same result like the following example:
<input name="numbersonly" type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" />
DEMO
See the Pen Input field that takes only numbers as value by Puneet Sharma (@webdevpuneet) on CodePen.