Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if the key pressed on a form field is a digit (0 - 9)?

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?

like image 657
wows Avatar asked Sep 09 '09 21:09

wows


People also ask

How do you check if the enter key is pressed?

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.

How do you check if a key is a Number JavaScript?

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”.

How do you check if string is a Number JavaScript?

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.


1 Answers

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,'');
like image 101
Gibolt Avatar answered Oct 27 '22 23:10

Gibolt