The accepted answer is already good, however if your requirement is that you would like your user to be able to navigate their input (by using either the left or right cursor keys) and possibly amend their input (by using either the delete or the backspace key on the keyboard), you may choose to use this method.
Another benefit of this method is that accepts numbers from both the top row of the keyboard in addition to numbers from the numeric keypad.
The input HTML element will look something like this...
<input type="number"
onkeydown="return validateIsNumericInput(event)"
...
any other attributes for the input element
>
The JavaScript function will look like this:
/**
Checks the ASCII code input by the user is one of the following:
- Between 48 and 57: Numbers along the top row of the keyboard
- Between 96 and 105: Numbers in the numeric keypad
- Either 8 or 46: The backspace and delete keys enabling user to change their input
- Either 37 or 39: The left and right cursor keys enabling user to navigate their input
*/
function validateIsNumericInput(evt) {
var ASCIICode = (evt.which) ? evt.which : evt.keyCode
permittedKeys = [8, 46, 37, 39]
if ((ASCIICode >= 48 && ASCIICode <= 57) || (ASCIICode >= 96 && ASCIICode <= 105)) {
return true;
};
if (permittedKeys.includes(ASCIICode)) {
return true;
};
return false;
}