Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

text field - numerical value

Status
Not open for further replies.

novice2004

Programmer
Feb 2, 2004
62
US
Would you please provide me with some code that when entering something into text field accepts just numerical value (onKeyPress)
Thank you.


<TD><INPUT TYPE="text" NAME="Year_Of_Birth" maxLength="4"size="4"></TD>
 
Rather than create a function that detects each keypress, it's a little easier, and uses a lot less system resources, if you just validate the code before submission. The theory behind this is that you have to build a function that detects the keypress (or key release), calls the function to check if it's a numeric value, then return control back to the user. In many cases, a user can out type the function - type faster than the function can respond - and this can confuse the user when there are alert boxes popping up unexpectedly.

There's always a better way. The fun is trying to find it!
 
Forgot to add that such a function will fire even if the user catches the error and tries to correct it by using BACKSPACE to fix his/her error.

There's always a better way. The fun is trying to find it!
 
isNaN() - or rather not isNan() - would do it.

You could also use parseInt() but be careful of leading zeros. If the first letter is a 0 (zero), parseInt() assumes the number to be an octal and so numbers with nine in them would be treated as invalid.

In your case since you want to vlidate only for years, you might write something like:

If length != 4 then error.
For i=0;i<4;i++
if (data < 0 || data > 9) then error; exit;
EndFor
Now validate for reasonableness of range.

HTH.
End

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top