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?
7: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!
6:52 am
Anonymous
is not really Integer because the input allow only positive numbers.
1:45 pm
Evan
Works perfectly for me (I only need positive integers), and I have no problem deleting the contents of the field.
11:20 am
Anonymous
Works in IE 7 but not in firefox 3.6.17 (prevents all keys from being entered).
11:21 am
Anonymous
Works in IE 7 but not in firefox 3.6.17 (prevents all keys from being entered).
1:29 pm
sky vegas rainbow riches
These are genuinely enormous ideas in concerning blogging.
You have touched some good factors here. Any way keep up wrinting.
2:18 am
Himanshu Saraswat
Works good in IE only. Does not work with Firefox
11:26 pm
Rex
Thanks for the help, I found a similar code here http://www.webstutorial.com/jquery-allow-only-numbers/jquery
Great work.
10: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));
}
6:51 am
iron-man
I appreciate the helpful information. Personally, I always leave a useful comment. I get plenty of useless, spammy comments on my own site that I have to get rid of.
stock market futures
Post new comment