[thelist] Why does this JS code work the way it does???

Anthony Baratta anthony at baratta.com
Mon Dec 11 12:52:51 CST 2006


Normally I can tear into a piece of code and figure out what it's doing. But I can't quite see why this JS function is working exactly the way it does. Here's the function, my comments follow:

function CheckNumericKeyStroke()
    var strValidKeys = "1234567890";
    if (strValidKeys.indexOf(String.fromCharCode(event.keyCode)) == -1)
        return false;
        return true;

Here's how it's put in use:

<input type="text" class="frmInputText2" style="width: 55px" 
   onkeypress="return CheckNumericKeyStroke();">

NOTE: I'm working with an IE only environment.

Now, here's what I don't understand - why do the backspace and delete keys work in the above text input element? They should comeback with "false" and not "fire". But they do. Why? IE quirk?

When I isolate the key code part "String.fromCharCode(event.keyCode)", and send the result as an alert to the browser on the onkeypress event - both backsapce and delete do not fire on that event. Is this by standards design?

Any pointers on this behaviour is appreciated.

More information about the thelist mailing list