How to Only Allow Numbers in a Text Box using jQuery?

We can easily allow only numbers in a textbox using jQuery. This is useful for form validation and ensures users can only enter numeric values in specific input fields. We will explore two different approaches to achieve this functionality.

  • Allow Only Numbers in a TextBox using jQuery replace() method
  • Allow Only Numbers in a TextBox using jQuery fromCharCode() method

Method 1: Using jQuery replace() with keyup Event

This method uses the keyup event to filter out non-numeric characters after they are typed. It uses a regular expression with the replace() method to remove any character that is not a digit (0-9) or decimal point.

Syntax

$('.selector').keyup(function () {
   this.value = this.value.replace(/[^0-9\.]/g,'');
});

The regular expression /[^0-9\.]/g matches any character that is not a digit (0-9) or decimal point (.), and the g flag ensures all occurrences are replaced.

Example

Following example demonstrates how to allow only numbers in textboxes using the replace() method

<!DOCTYPE html>
<html>
<head>
   <title>Input Numbers Only - Replace Method</title>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h1>Score Entry Form</h1>
   <p>Rank: <input type="text" class="numbers" placeholder="Enter rank" /></p>
   <p>Marks: <input type="text" class="numbers" placeholder="Enter marks" /></p>
   <p><em>Try typing letters or special characters - they will be automatically removed!</em></p>
   
   <script>
      $('.numbers').keyup(function () {
         this.value = this.value.replace(/[^0-9\.]/g,'');
      });
   </script>
</body>
</html>

In this example, any non-numeric characters typed into the textboxes with class numbers will be automatically removed as soon as the user releases the key.

Method 2: Using jQuery fromCharCode() with keypress Event

This method prevents non-numeric characters from being entered in the first place by using the keypress event. It checks the character code of the pressed key and blocks it if it's not a digit.

Syntax

$('.selector').keypress(function (e) {
   if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});

The String.fromCharCode(e.keyCode) converts the key code to its corresponding character, and if it matches non-numeric characters, the function returns false to prevent the character from being entered.

Example

Following example demonstrates preventing non-numeric input using the fromCharCode() method

<!DOCTYPE html>
<html>
<head>
   <title>Input Numbers Only - fromCharCode Method</title>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h1>Student Information</h1>
   <p>Student ID: <input type="text" class="numbers" placeholder="Enter ID" /></p>
   <p>Age: <input type="text" class="numbers" placeholder="Enter age" /></p>
   <p><em>Try typing letters - they won't appear in the input fields!</em></p>
   
   <script>
      $('.numbers').keypress(function (e) {
         if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
      });
   </script>
</body>
</html>

With this approach, non-numeric keys are blocked before they can appear in the input field, providing immediate feedback to the user.

Enhanced Method: Allowing Decimal Numbers and Negative Values

For more advanced use cases, you might want to allow decimal numbers or negative values. Here's an enhanced version

<!DOCTYPE html>
<html>
<head>
   <title>Enhanced Number Input</title>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h1>Enhanced Number Validation</h1>
   <p>Price: <input type="text" class="decimal-numbers" placeholder="e.g., 99.99" /></p>
   <p>Temperature: <input type="text" class="signed-numbers" placeholder="e.g., -15.5" /></p>
   
   <script>
      // Allow digits and one decimal point
      $('.decimal-numbers').keyup(function () {
         this.value = this.value.replace(/[^0-9\.]/g,'');
         // Ensure only one decimal point
         var parts = this.value.split('.');
         if (parts.length > 2) {
            this.value = parts[0] + '.' + parts.slice(1).join('');
         }
      });
      
      // Allow digits, decimal point, and minus sign at the beginning
      $('.signed-numbers').keyup(function () {
         var value = this.value.replace(/[^0-9\.\-]/g,'');
         // Ensure minus only at the beginning
         if (value.indexOf('-') > 0) {
            value = value.replace(/-/g, '');
         }
         this.value = value;
      });
   </script>
</body>
</html>

Comparison of Methods

Method Event Used Behavior User Experience
replace() with keyup keyup Allows typing, then removes invalid characters User sees character briefly before it's removed
fromCharCode() with keypress keypress Prevents invalid characters from appearing Invalid characters never appear in the field
Enhanced validation keyup Custom logic for specific number formats Supports decimals and negative numbers

Key Points

  • The keyup method is more flexible and allows for complex validation logic
  • The keypress method provides immediate feedback and prevents invalid input
  • Regular expressions are used to define what characters are allowed or forbidden
  • Both methods can be applied to multiple input fields using CSS class selectors
  • Consider using HTML5 input type="number" as an alternative for basic numeric input

Conclusion

Both jQuery methods effectively restrict text input to numbers only. The keyup with replace() method is more flexible for complex validation, while the keypress with fromCharCode() method provides immediate prevention of invalid characters. Choose the method that best fits your user experience requirements and validation needs.

Updated on: 2026-03-16T21:38:54+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements