Good moring programmers, I'm new to this forum and relatively new to Javascript; I hope that this makes sense. I've written a function to filter all key strokes from a HTML <input> using the onkeypress="return keyPressed()" event. The keyPressed() function returns true if the digits 0-9 are entered on either the main keyboard or the numeric keyboard, it returns false if any other key is entered. My problem is that the keys a-i are returning the same keycodes and the 1-9 digits on the numeric keyboard if the Caps Lock is off. If the Caps Lock is on, the a-i keys return the correct keycodes. Here is a partial listing of my code: function keyPressed() { //Allow the entry of digits 0 to 9. var validChar=[48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105]; var KC; if(window.event) { KC=event.keyCode; } else { KC=e.keyCode; } //more code to return either true or false } Code (markup): As I step through the code I can see the variable KC and the keycode that was returned. Any suggestions would be greatly appreciated.
Use onkeypress instead of onkeydown or onkeyup: <script type="text/javascript"> function poop(e) { if(!(e.charCode >=48 && e.charCode <= 57)) alert("Numbers only."); } </script> <input type="text" onkeypress="return poop(event);" size="30" /> HTML: See this for differences.
Rainulf, Thank you for your assistance. I have been using onKeyPress; my problem was understanding what was returned by different browsers. Your link was very helpful. The characrer codes in IE are undefined and the keycodes in Firefox are undefined for the onKeyPress event. I also thought that the keycodes returned by 0-9 on the numeric keypad were different than 0-9 on the main keyboard. My code is now: function keyPressed(e) { //Allow the entry of digits 0 to 9. var KC = (window.event) ? event.keyCode : e.charCode; if(KC>47 && KC<58) { return true; } else { return false; } } Code (markup): With this code I can enter only digits from either the main or numeric keyboards using either the IE or Firefox browser. However I cannot yet claim success; the delete and backspace keys do not work on Firefox, but they do on IE, and I haven't considered the MAC plarform yet. Again thanks for your help; the test site really let me look at what was going on.
The bombproof solution to this one is to forget about keycodes and use the onkeyup event to strip all unwanted characters from the input field.