Efficiently Restricting Text Field to Numbers Only with JavaScript

Restricting a text field to only allow numbers can be a helpful feature for forms that require numerical input. With JavaScript, this can be achieved by adding an event listener to the text field that checks each key pressed and only allows numerical input.

  1. Code Example:
    1. Explanation of Code:

Code Example:

<input type="text" id="numberInput">

const numberInput = document.getElementById("numberInput");

numberInput.addEventListener("keydown", function(event) {
  // Allow: backspace, delete, tab, escape, enter and .
  if ([46, 8, 9, 27, 13, 110, 190].indexOf(event.keyCode) !== -1 ||
      // Allow: Ctrl+A
      (event.keyCode === 65 && event.ctrlKey === true) || 
      // Allow: Ctrl+C
      (event.keyCode === 67 && event.ctrlKey === true) || 
      // Allow: Ctrl+X
      (event.keyCode === 88 && event.ctrlKey === true) || 
      // Allow: home, end, left, right
      (event.keyCode >= 35 && event.keyCode <= 39)) {
           // let it happen, don't do anything
  // Ensure that it is a number and stop the keypress
  if ((event.shiftKey || (event.keyCode < 48 || event.keyCode > 57)) && (event.keyCode < 96 || event.keyCode > 105)) {

The above code attaches an event listener to an input field with an ID of "numberInput". The listener will only allow numerical input by checking the keyCode of each key pressed. It also allows certain keys such as backspace and delete for editing purposes.

Explanation of Code:

  • The event listener is attached to the input field using the addEventListener() method.
  • The first part of the listener checks if the keyCode of the pressed key is in an array of allowed keys. If it is, the function returns and does not prevent the keypress.
  • If the key pressed is not an allowed key, the function checks if it is a number. If it is not a number, the preventDefault() method is called to stop the keypress from registering.
  • The shiftKey property is used to check if the shift key is pressed, allowing the user to type certain characters such as !,@,#,$, etc.

By using this code, you can efficiently restrict a text field to only allow numerical input, improving the user experience and ensuring correct form submissions.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information