It is very common to have fields that should only contain integers, or numbers of some sort. For example: zip codes, dollar amounts, age field, and so on. Well instead of having to perform a round trip to the server to check for the proper data type, you can do it right in the client browser. This JavaScript function will capture a user's input, and only allow it if it's a number.
The verification takes place based on the keycode. I've added in the keycodes for periods and colons, just in case the field is for a date or time. To get this to work on a field, just add the attribute: onKeyDown="return KeyCheck( this );".
function KeyCheck( myfield ) {
var keycode;
if ( window.event ) {
keycode = window.event.keyCode;
} else if ( event ) {
keycode = event.keyCode;
} else {
return true;
}
//alert( keycode )
if ( ( ( keycode > 47 ) && ( keycode < 58 ) ) || ( keycode == 8 ) || ( keycode == 186 /* : */ ) || ( keycode == 110 /* . */ ) || ( keycode == 190 /* . */ ) ) {
return true;
} else {
return false;
}
}
And here's an example of how to use it:
<input type="text" name="age" onKeyDown="return KeyCheck( this );" />
Sign up for our daily email newsletter:
You must log in to post a comment.