HTML
jQuery
Input Validation
Web Development
Numeric Input

How to allow only numeric (0-9) in HTML inputbox using jQuery?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

To create a user-friendly form in an HTML application, ensuring input data quality is crucial. A common requirement is to restrict input in a text box to numeric values only (0-9). Using jQuery, a fast, small, and feature-rich JavaScript library, can simplify this task. Below, we explore how to implement this with detailed steps and examples.

Understanding the Need for Numeric Input Validation

Input validation is vital for many reasons:

  • Security: Prevents malicious data from being entered.
  • Data Integrity: Ensures the data is in the expected and required format.
  • User Experience: Provides immediate feedback to users about invalid entries.

Using jQuery to Restrict Inputs to Numeric Characters

Step 1: Setup Your HTML and jQuery

Firstly, ensure your web page is set up to use jQuery. If it's not already included, you can add it through a CDN (Content Delivery Network) like so:

html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

With jQuery included, you can now add an HTML input box where numeric input will be restricted:

html
<input type="text" id="numeric-input" placeholder="Enter numbers only">

Step 2: Implementing jQuery to Restrict Non-Numeric Characters

To restrict user input to numeric characters, you can bind an event to the input element that reacts every time a user presses a key. Here's how to do it using jQuery:

javascript
1$(document).ready(function(){
2  $('#numeric-input').keydown(function(event){
3    // Allow only backspace, delete, tab, escape, enter, and numeric keys
4    if ($.inArray(event.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
5       // Allow: Ctrl/cmd+A
6       (event.keyCode === 65 && (event.ctrlKey === true || event.metaKey === true)) ||
7       // Allow: Ctrl/cmd+C
8       (event.keyCode === 67 && (event.ctrlKey === true || event.metaKey === true)) ||
9       // Allow: Ctrl/cmd+X
10       (event.keyCode === 88 && (event.ctrlKey === true || event.metaKey === true)) ||
11       // Allow: home, end, left, right
12       (event.keyCode >= 35 && event.keyCode <= 39)) {
13         // let it happen, don't do anything
14         return;
15    }
16    // Ensure that it is a number and stop the keypress
17    if ((event.shiftKey || (event.keyCode < 48 || event.keyCode > 57)) && 
18       (event.keyCode < 96 || event.keyCode > 105)) {
19      event.preventDefault();
20    }
21  });
22});

Explanation:

  • The keydown event triggers whenever a key is pressed.
  • The $.inArray() function checks whether the key code of the key pressed is amongst common non-character keys like backspace (8), tab (9), enter (13), etc., that should be allowed for functional purposes.
  • We check for modifier keys combined with letters like 'A' (for select all), 'C' (for copy), and 'X' (for cut).
  • Finally, numeric keys on the keyboard (both top-row numbers and keypad numbers) are explicitly checked, and other character inputs are prevented using event.preventDefault().

Summary Table of Allowed Key Codes

KeyKey Code
Backspace8
Tab9
Enter13
Escape27
Delete46
Ctrl/cmd+A65
Ctrl/cmd+C67
Ctrl/cmd+X88
Home35
End36
Arrow Left37
Arrow Up38
Arrow Right39
Arrow Down40
Numeric keys 0-948-57
Keypad keys 0-996-105

Enhancing Functionality

To improve the user experience further, consider adding visual feedback or error messages when non-numeric characters are entered. You can also use HTML5 input types like <input type="number">, though these behave slightly differently across browsers and do not restrict key presses.

Implementing numeric input validation with jQuery is an effective way to ensure data quality and enhance security and usability in form inputs.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.