How to Check if the Key Pressed is a Number using JavaScript?

To check if the key pressed is a number or not, you can use event.keyCode or event.which property. Both properties return the Unicode value of the key pressed.

We know that the Unicode value of 0 is 48, Unicode value of 1 is 49, and so on up to 57 which is the Unicode value of 9. So, if the Unicode value of the key pressed lies between 48 to 57(including), it is a number otherwise not.

Let’s say we have a text input box in our HTML file with some id myInput:

<input type="text" id="myInput" placeholder="Type something">

Now, let’s add an event listener to this input so that we could listen to the keyup event. The keyup event is fired whenever we press a key and release it.

Next, in the event listener function, we need to check if the key code of the pressed key is between 48 to 57 or not. If yes, then the pressed key is a number otherwise not.

const input = document.getElementById('myInput');

input.addEventListener('keyup', function(event){
    let keycode = event.keyCode || event.which;
    
    if(keycode>=48 && keycode<=57){
        
        alert("You have pressed a number key");
        // Use event.key to get key name
        
    }else{
        
        alert("You haven't pressed a number key");
        
    }
});

You can also use the event.key property to check if the pressed key is a number or not. The event.key property returns the name of the pressed key as a string eg. ‘0’, ‘1’, ‘a’, ‘Enter’, etc.

So, we can create a numbers array which will contain all digits from 0 to 9 as a string and then check if the key pressed is in the numbers array or not using the Array.indexOf() method.

The Array.indexOf() method returns the index of the element if it is found in the array otherwise it returns -1:

const input = document.getElementById('myInput');
const numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

input.addEventListener('keyup', function(event){
    
    if(numbers.indexOf(event.key)!=-1){
        
        alert("You have pressed a number key");
        // Use event.key to get key name
        
    }else{
        
        alert("You haven't pressed a number key");
        
    }
});

Thanks for reading.


Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts