"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: