Javascript numeric only text box
So working on an asp.net page I found I needed a numeric only text box that allowed numbers from 0-100 with no decimals. I found a range validator would do most of the work but I wanted to keep users from typing in bad values. So after some searching I found javascript has a good solution. I like whitespace so shrink if you're one of those white space freaks.
Update: someone was kind enough to point out an error in my JS! So I went through and made sure it works. And it did need a minor tweak to be correct. So thanks to the poster the corrected script and usage are below.
Update Again:
This is the new and improved function to allow for the tab key to tab out of the text box. IE allows this by default however Firefox really tightens down the text box and doesn't allow anything you don't specify. So I had to add the tab key press. I also cleaned up the code so it isn't a huge chunk of if blocks and is now much more succinct. Please feel free to test and use at will. To modify to allow different key presses you just need to modify the if statement.
The javascript:
The usage:
<input type="text" name="textbox1" id="textbox1" onkeypress="return numeric_only(event);" />
Update: someone was kind enough to point out an error in my JS! So I went through and made sure it works. And it did need a minor tweak to be correct. So thanks to the poster the corrected script and usage are below.
Update Again:
This is the new and improved function to allow for the tab key to tab out of the text box. IE allows this by default however Firefox really tightens down the text box and doesn't allow anything you don't specify. So I had to add the tab key press. I also cleaned up the code so it isn't a huge chunk of if blocks and is now much more succinct. Please feel free to test and use at will. To modify to allow different key presses you just need to modify the if statement.
The javascript:
// function to only allow numeric key presses in a textbox
// this doesn't stop pasting of non numeric values
function numeric_only( e )
{
// deal with unicode character sets
var unicode = e.charCode ? e.charCode : e.keyCode;
// if the key is backspace, tab, or numeric
if( unicode == 8 || unicode == 9 || ( unicode >= 48 && unicode <= 57 ) )
{
// we allow the key press
return true;
}
else
{
// otherwise we don't
return false;
}
}
The usage:
<input type="text" name="textbox1" id="textbox1" onkeypress="return numeric_only(event);" />
Comments
Works great!
(tested in
FireFox 2.0 vista
safari 1.3.2 OSX 10.3.9
IE 7.0.6 vista)
Glad it worked out for you. Thanks for posting how broken my code was!
Justin
really nice
thankS!
every1 shd make this clean +simple code
Great Simple easy to Use. Could not have done better myself
Thank you a ton!
What browser are you running?
if (unicode != 8 && unicode != 9 && unicode != 46)
{
// Rest processing
}