HTML Restricting a Field to Numbers OnlyThe previous page demonstrated a technique for restricting form field inputs to just letters and numbers. This page shows a technique for restricting the field to just numbers. The script also allows you to automatically jump to the next field if the user presses the decimal key.
First, copy this script exactly as-is into the
<SCRIPT TYPE="text/javascript">
<!--
function numbersonly(myfield, e, dec)
{
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
// control keys
if ((key==null) || (key==0) || (key==8) ||
(key==9) || (key==13) || (key==27) )
return true;
// numbers
else if ((("0123456789").indexOf(keychar) > -1))
return true;
// decimal point jump
else if (dec && (keychar == "."))
{
myfield.form.elements[dec].focus();
return false;
}
else
return false;
}
//-->
</SCRIPT>
Now we can create a numbers only field using the
<FORM ACTION="/cgi-bin/mycgi.pl" METHOD=POST> U.S. ZIP Code: <INPUT NAME="dollar" SIZE=5 MAXLENGTH=5 onKeyPress="return numbersonly(this, event)"> <INPUT TYPE=SUBMIT VALUE="go"> </FORM> This gives us this form: U.S. ZIP Code: (Form is not live)
Here's what happens. When the user presses a key, In the next page we'll show you how to have the cursor automatically jump to the next field when the user presses the decimal point thus creating a two-part numeric field. Numbers Only: Jumping at the Decimal Point > |