↑
Main Page
Numeric text boxes with the up/down arrow keys
A similar method is needed to use with
allowChars()
. This method, called
blurAllow()
, is almost
exactly the same as
blurBlock()
, only it makes sure that every character in the text box is valid:
TextUtil.blurAllow = function(oTextbox) {
var sValidChars = oTextbox.getAttribute(“validchars”);
var arrTextChars = oTextbox.value.split(“”);
for (var i=0; i< arrTextChars.length; i++){
if (sValidChars.indexOf(arrTextChars[i]) == -1) {
alert(“Character ‘“ + arrTextChars[i] + “‘ not allowed.”);
oTextbox.focus();
oTextbox.select();
return;
}
}
};
Notice this method begins by retrieving the valid characters from the
validchars
attribute, just as in
allowChars()
. The next step is to split the text in the text box into an array of characters because each
character must be checked for validity. The method loops through the array, checking to see if each char-
acter is contained in the
sValidChars
string. When it encounters a character that isn’t valid (meaning
that
indexOf()
returns –1, indicating that the given character doesn’t exist in
sValidChars
), an alert is
displayed showing the illegal character. Then, just as in
blurBlock()
, focus is shifted to the text box,
text is selected, and the method exits. This method is used like this:
<input type=”text” onkeypress=”return TextUtil.allowChars(this, event)”
validchars=”0123456789” onblur=”TextUtil.blurAllow(this)” />
The end result of this is a way that does not prevent a user from pasting illegal values, but it ensures that
if an illegal value is pasted in, the user is notified right away.
Numeric text boxes with the up/down arrow keys
Suppose you’ve implemented a numbers-only text box using the
TextUtil.allowChars()
method,
but that still isn’t enough to make your users happy. What they really want is the capability to press the
up arrow and down arrow keys in order to increment and decrement the number. To address this, use
the
onkeydown
event handler.
You may be wondering why this code uses the
onblur
event handler instead of
onchange
. Logically, because the
change
event fires when the value in a text box
changes and then the text box loses focus, this would seem to be the perfect way to
check for pasted values. Consider what happens as this code is executed. First, the
user pastes an illegal value into the text box and tries to tab to the next field. The
change
event fires here, as will
blur
. The user is presented with an alert saying that
an illegal character has been found, and focus is shifted back to the text box. For some
reason, the user doesn’t fix the illegal character, but instead tabs forward once again.
This time, the
change
event doesn’t fire because the value in the text box hasn’t
changed since it got focus. The
blur
event, however, still fires.
354
Chapter 11
14_579088 ch11.qxd 3/28/05 11:40 AM Page 354
Free JavaScript Editor
Ajax Editor
©
→