Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnKeyDown and String.FromCharCode

i've a question concerning the OnKeyDown event. The OnKeyDown event gives a KeyCode but I don't know exactly what kind of code is given. Basically, I was using the String.FromCharCode method to get the real character from what I thought was the ASCII-Code. It worked fine until I tried with the numbers from the numpad. If I type the '2' using the key above 'w' that's ok, but with the '2' from the numpad the KeyCode given is 98 (which is 'b' Ascii code).

I was looking at this page and there's the same problem. The example is supposed to prevent the user from typing numbers. It works perfectly fine with the numbers on top of the first character (for lack of a better name), but you can type numbers using the num pad.

Do you have any idea what the problem is? (is this really the ascii code ? Am I using the wrong event ? )...

thx...

like image 715
LB40 Avatar asked Dec 12 '22 16:12

LB40


2 Answers

To prevent numbers use onkeypress instead:

onkeypress="return PreventDigits(event);"
...
function PreventDigits(evt) {
    evt = evt || window.event;
    var keyCode = evt.keyCode || evt.which;7
    var num = parseInt(String.fromCharCode(keyCode), 10);
    return isNaN(num);
}

Live example: http://jsfiddle.net/yahavbr/vwc7a/

like image 186
Shadow Wizard Hates Omicron Avatar answered Jan 06 '23 12:01

Shadow Wizard Hates Omicron


keyCode and charCode are different animals. keyCode relates to the keyboard and the key loayout, whereas the charCode actually gives the ascii character code.

Further there is a lot of bad in the different implementations of key events. I always liked this page as a good source: http://unixpapa.com/js/key.html

Edit: As Raynos says, skip w3schools when it comes up in Google searches.

like image 44
Hemlock Avatar answered Jan 06 '23 11:01

Hemlock