Thursday, February 17, 2005

Limiting Characters entered in an html text field Part 1

This script allows numeric, & decimal. You also have to filter out the Home, End, & Arrow keys so they can be used. When you call the function, you must be sure to pass the event. The event to call when filtering keys is the onkeypress event. Notice that the function returns a true or false; and the onkeypress event in the html returns this value so that the body knows whether to allow the key or not. This function filters on IE or Netscape. The "evt.which" statement is the Netscape equivalent to IE's "evt.keyCode."

This is the script that should go in your <head></head>:

<script type="text/javascript">
//Allows only 0-9 & .(decimal)
//The Home, End, & Arrow Keys had to be filtered as well
function checkKey(evt)
{
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
if (evt.shiftKey)
{
return false;
}
if (charCode > 31 && (charCode < 48 charCode > 57))
{
if (charCode == 110 charCode == 190 charCode == 46 (charCode >= 35 && charCode <= 39))
{/*Do nothing...we want these characters allowed.*/}
else if (charCode < 96 charCode > 106)
{
return false;
}
}
return true;
}
</script>


This is an example of the html that should go in your <body></body>:

<body>
<input type="text" onkeypress="return checkKey(event);" id="number"/>
</body>


NOTE: The JavaScript used above uses the single line if-statement. Please see my posting about the single line if-statement for an explanation on how to use this.

1 comment:

Anonymous said...

Hey. It's a good script, but it can be fooled if you press two keys alphabetic keys at one time.