I'm using the onkeyup
event on a form field in JavaScript, and I'm wanting to check if the key the key pressed is a numeric digit - i.e. 0 - 9, so I can then do something with the input.
<input type="text" onkeyup="" />
Would I need to use Regex for this?
To check if an “enter” key is pressed inside a textbox, just bind the keypress() to the textbox. $('#textbox'). keypress(function(event){ var keycode = (event.
In JavaScript, there are two ways to check if a variable is a number : isNaN() – Stands for “is Not a Number”, if variable is not a number, it return true, else return false. typeof – If variable is a number, it will returns a string named “number”.
Use the isNaN() Function to Check Whether a Given String Is a Number or Not in JavaScript. The isNaN() function determines whether the given value is a number or an illegal number (Not-a-Number). The function outputs as True for a NaN value and returns False for a valid numeric value.
Use event.key
to get the actual value. To check if integer, just use isFinite
input.addEventListener("keydown", function(event) {
const isNumber = isFinite(event.key);
});
Other option:
const isNumber = /^[0-9]$/i.test(event.key)
An easier HTML solution would be to use the number
type input. It restricts to only numbers (kind of).
<input type="number">
Either way, you should clean all user input with:
string.replace(/[^0-9]/g,'');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With