JavaScript Code

JavaScript – Only Allow Numbers in a Field

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;
    }
}
&#91;/code&#93;
And here's an example of how to use it:
&#91;code lang="html"&#93;
<input type="text" name="age" onKeyDown="return KeyCheck( this );" />
Share

1 Comments

  1. SHOW SOME EXAMPLES CAN? I MEAN PRINTSCREEN.

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image