|
Dealing with Special Keys
Some keys don't produce visible characters, so you must use their ASCII codes to test for the keystrokes. You know the keycode that each key produces thanks to the alert in Example 3.
Backspace and Enter For example, Backspace and Enter don't produce visible characters. Backspace is keycode 8 or hex 08 and Enter is keycode 13 or hex 0D. You can modify the handler by adding a regular expression that allows normal operation of the Backspace and Enter keys.
var reKeyboardChars = /[\x08\x0D]/;
In regular expressions, you can represent a character by using \x followed by two hexadecimal digits (0 through F). This regular expression matches either the keycode of the Backspace key or the keycode of the Enter key. The square brackets act as a logical OR that will match either of the two keycodes specified.
Add the new regular expression into the maskKeyPress() function from Example 3:
function maskKeyPress(objEvent) {
var iKeyCode, strKey;
if (isIE) {
iKeyCode = objEvent.keyCode;
} else {
iKeyCode = objEvent.which;
}
strKey = String.fromCharCode(iKeyCode);
if (!reValidChars.test(strKey) &&
!reKeyboardChars.test(strKey)) {
alert("Invalid Character Detected!\nKeyCode = " +
iKeyCode + "\nCharacter =" + strKey);
return false;
}
}
Example 4 shows the modified maskKeyPress() function in action. Now you can press the Backspace or Enter key without firing an invalid character alert.
Home, End, Delete, and Arrows You can deal with the next four behaviors as a group, the Home, End, and Delete keys. Fortunately, the Home, End, Delete and arrow keys work fine in NS4 and IE, but NS6 has a problem.
Whenever you press any of these keys in NS6, you get the invalid character alert, but every alert shows a keycode of 0, regardless of which key you press. So even though NS6 fires the keypress event for these keys, you have a simple way of knowing that these particular keys have been pressed.
So for NS6 you must add a check for an ASCII code of 0 to the regular expression:
var reKeyboardChars = /[\x00\x08\x0D]/;
Example 5 is identical to Example 4 except that it contains the updated regular expression. Adding the ASCII code 0 to this regular expression doesn't affect the behavior for the other browsers' behavior. At this point, you can restrict the user to entering only numbers into the textbox, but you still need to add the ability to recognize common functions.
|
|
 |
TALK
BACK |
|
Creating a masked edit text box in DTHML is not as straightforward as it seems at first. Do you know of other masked edit examples? Join the discussions at web.dhtml.scripting to get answers, make comments, or help others with their problems.
|
|
|
|
|
|
|