Logo

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

Below are a few methods to restrict an <input> element to numeric digits (0–9) using jQuery. Keep in mind that client-side validations aren’t foolproof—always do server-side validation as well.

1. Filter Keystrokes with Key Events

You can listen for keydown, keypress, or input events and prevent or remove invalid characters. Below is an example using keydown:

<input type="text" id="numericInput">
$(document).ready(function() { $("#numericInput").on("keydown", function(e) { // Allow: backspace, delete, tab, escape, enter, left/right arrows if ( $.inArray(e.keyCode, [46, 8, 9, 27, 13, 37, 39]) !== -1 || // Allow: Ctrl+A, Ctrl+C, Ctrl+V, Ctrl+X, etc. (e.ctrlKey === true && (e.keyCode === 65 || e.keyCode === 67 || e.keyCode === 86 || e.keyCode === 88)) || // Allow: home, end, function keys (F1-F12) (e.keyCode >= 35 && e.keyCode <= 40) ) { // Let it happen return; } // Ensure that it is a number and stop the keypress if not if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { e.preventDefault(); } }); });

Explanation:

  1. We allow special keys (Backspace, Delete, Tab, Escape, Enter, arrow keys).
  2. We permit common keyboard shortcuts (Ctrl + A, C, V, X).
  3. If the key is not a digit in both the numeric row (48–57) or keypad row (96–105), we call e.preventDefault() to disallow it.

Pros: Real-time restriction while typing.
Cons: Users can still paste invalid text or use drag/drop. You should handle that too.

2. Auto-Remove Invalid Characters on input

Another approach is to let the user enter text, but immediately strip out non-numeric characters:

<input type="text" id="numericInput2">
$(document).ready(function() { $("#numericInput2").on("input", function() { // Replace everything not [0-9] with an empty string this.value = this.value.replace(/[^0-9]/g, ''); }); });

Pros: Simple, handles pasting and drag/drop automatically.
Cons: Doesn’t block keystrokes in real-time, but does quickly revert invalid input.

3. Combine Both Approaches

You can combine the keypress or keydown filter for immediate feedback with the oninput fallback to catch any invalid input from paste or other methods:

$("#numericInput").on("keydown", function(e) { // Filter out non-digit keystrokes (like in the first example) }); $("#numericInput").on("input", function() { this.value = this.value.replace(/[^0-9]/g, ''); });

4. Use a <input type="number"> with JavaScript Validation

A more semantic approach is:

<input type="number" id="numericInput" />

You can also specify HTML attributes like min="0".
However, some browsers allow special characters like e (for exponent) or - (minus) if you don’t set min or certain other constraints.

$("#numericInput").on("input", function() { // Ensure the input remains an integer this.value = this.value.replace(/[^0-9]/g, ''); });

Pros: Built-in numeric keyboard on mobile devices.
Cons: May allow non-integer values or exponents depending on the browser.

Best Practices

  1. Server-Side Validation: Even if you restrict the input, always validate on the server or final submission.
  2. User Experience: Decide whether you want to block invalid keystrokes right away or auto-correct after input.
  3. Edge Cases: Consider if you need to handle empty string, leading zeros, or large numbers.

Level Up Your Web Development Skills

To gain deeper insights into front-end best practices and JavaScript fundamentals, consider these courses on DesignGurus.io:

These resources offer practical, pattern-based approaches, helping you build robust input-handling, form validation, and much more. Additionally, for free tutorials on coding interviews, system design, and front-end techniques, check out the DesignGurus.io YouTube channel.

CONTRIBUTOR
TechGrind