<HTML>
<HEAD>
<TITLE>Allow Only Numbers
</HEAD>
<BODY>
<script language="JavaScript">
function onlyNumbers(evt)
{
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
<input type="text" onkeypress="return onlyNumbers();">
</BODY>
</HTML>
Not so smart. This doesn't allow for the shift key being pressed, so allows any of !"£$%^&*() as well as any numeric.
Obviously (??) the onKeyDown etc doesnt detect Shift1 etc.
So as a validation before assigning to a numeric field then this just doesnt work.The problem with the shift key can be fixed as follows :
{
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
if (e.shiftkey) return false;
return true;
}
The down side of this is that it efectively disables the numeric key pay because the Num Lock sets the shift key.
<HTML>
<HEAD>
<SCRIPT language=Javascript>
<!--
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
</BODY>
</HTML>
No comments:
Post a Comment