Main Page

numericScroll

You may ask, why not just use the
onkeypress
event handler again? The answer is that the
keypress
event only fires for those keys that represent characters in a text box. Because the arrow keys don’t cause
a character to be put into the text box, the
keypress
event won’t fire. The
keydown
event, however, fires
no matter what kind of key is pressed.
To make sure you’re only dealing with the up and down arrow keys, use the
keyCode
property of
event
.
The code for the up arrow is 38 and the code for the down arrow is 40. All other keys can be ignored:
TextUtil.numericScroll = function (oTextbox, oEvent) {
oEvent = EventUtil.formatEvent(oEvent);
var iValue = oTextbox.value.length == 0 ? 0 :parseInt(oTextbox.value);
if (oEvent.keyCode == 38) {
oTextbox.value = (iValue + 1);
} else if (oEvent.keyCode == 40){
oTextbox.value = (iValue - 1);
}
};
Once again, the
EventUtil.formatEvent()
method is used to ensure the
event
object is properly for-
matted. The next step is to determine the integer value of the text. If there is some text in the text box, the
parseInt()
function is used to convert the value; otherwise, the value is assumed to be zero. Then, the
keyCode
property of the event is tested to see whether it’s the up arrow or down arrow. Depending on
the
keyCode
, the integer value is either incremented or decremented and then placed in the text box. The
method must be used in conjunction with the
allowChars()
(and either way of dealing with pasted
values) to ensure that only numeric values are present in the text box.
The method is used like this:
<input type=”text” onkeypress=”return TextUtil.allowChars(this, event)”
validchars=”0123456789” onblur=”TextUtil.blurAllow(this)”
onkeydown=”TextUtil.numericScroll(this, event)” />
This simple addition now enables the up and down keys to change the numeric value of the text box.
What else could you possibly want? How about a minimum value and a maximum value? By adding
two custom attributes,
min
and
max
, and updating the method, you can add the capability to specify a
minimum and maximum value to scroll to:
TextUtil.numericScroll = function (oTextbox, oEvent) {
oEvent = EventUtil.formatEvent(oEvent);
var iValue = oTextbox.value.length == 0 ? 0 :parseInt(oTextbox.value);
var iMax = oTextbox.getAttribute(“max”);
var iMin = oTextbox.getAttribute(“min”);
if (oEvent.keyCode == 38) {
if (iMax == null || iValue < parseInt(iMax)) {
oTextbox.value = (iValue + 1);
}
} else if (oEvent.keyCode == 40){
355
Forms and Data Integrity
14_579088 ch11.qxd 3/28/05 11:40 AM Page 355


JavaScript EditorFree JavaScript Editor     Ajax Editor


©