"Innovation comes only from readily and seamlessly sharing information rather than hoarding it."- Tom Peters
Development Blog

Creating input fields that only accept integers - jQuery

Wouldn't it be nice to force only certain characters into a text field? How about for a field asking for age? You would only want integers. Same with height, weight, or even a phone number. Well, here's a quick snippet that'll do just that!


$(document).ready(function() {
$("#inputField").keypress(function(event) {
return /\d/.test(String.fromCharCode(event.keyCode));
});
});

So, what's happening here? Well, it adds a keypress event to the input field with id "inputField" (feel free to change to whatever you need). Whenever a key is pressed, this function is fired. If the function returns false, the key pressed is not added to the input field. If it returns true, it is added.

The function is given an Event object, and the keyCode value is a numeric value. The String.fromCharCode converts that to the actual character that the user inputted. It is then tested if that character was an integer, using a regular expression test. If it is not an integer, false is returned, and the character is not added to the field! Pretty simple, huh?

Demo:


Anonymous's picture
Nov 18, 2010
6:55 am
Anonymous

Life ain't that simple! With your solution you can't paste any data into the input field, you can't even delete your input using the del or the backspace key. To achieve all of that, you need some 60 lines of code!

Anonymous's picture
Apr 1, 2011
5:52 am
Anonymous

is not really Integer because the input allow only positive numbers.

Evan's picture
May 19, 2011
12:45 pm
Evan

Works perfectly for me (I only need positive integers), and I have no problem deleting the contents of the field.

Anonymous's picture
Jun 29, 2011
10:20 am
Anonymous

Works in IE 7 but not in firefox 3.6.17 (prevents all keys from being entered).

Anonymous's picture
Jun 29, 2011
10:21 am
Anonymous

Works in IE 7 but not in firefox 3.6.17 (prevents all keys from being entered).

Himanshu Saraswat's picture
Sep 29, 2011
1:18 am
Himanshu Saraswat

Works good in IE only. Does not work with Firefox

Rex's picture
Jul 18, 2012
10:26 pm
Rex

Thanks for the help, I found a similar code here http://www.webstutorial.com/jquery-allow-only-numbers/jquery

Great work.

Rodrigo's picture
May 6, 2013
9:49 am
Rodrigo

Nice job. To get it working on FF and have the backspace enable I did something like this:
var code = event.charCode || event.keyCode;
if (event.keyCode == 8)
return true;
else {
return /\d/.test(String.fromCharCode(code));
}