Checking Which Key Was Pressed
Before reading through this page, you might want to check out these solutions first:
<SCRIPT TYPE="text/javascript">
<!--
function getkey(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
//-->
</SCRIPT>
In its simplest use,
<INPUT onKeyPress="window.status = getkey(event)"> This gives us this form: Most of the time you'll want to useonKeyPressgoodchars() uses getkey() so make sure you copy both of them into your page.
<SCRIPT TYPE="text/javascript">
<!--
function goodchars(e, goods)
{
var key, keychar;
key = getkey(e);
if (key == null) return true;
// get character
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
goods = goods.toLowerCase();
// check goodkeys
if (goods.indexOf(keychar) != -1)
return true;
// control keys
if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )
return true;
// else return false
return false;
}
//-->
</SCRIPT>
<INPUT NAME=INT onKeyPress="return goodchars(event,'0123456789')"> Which gives us this form: Be sure to put the wordreturn before the call to goodchars() or the event won't be cancelled if the user presses a wrong key. goodchars() is case-insensitive. If you allow "X" you also automatically allow "x".
goodchars() allows the standard editing keys such as backspace and delete.
|