8

I'm using keydown event

Where I get the keycode and convert it to charcode.

But I got a problem where in keyboard is press 2 it gives 50 and charcode as 2

When I press 2 in numpad it gives keycode 98, so when I convert charcode a

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Santhosh
  • 19,616
  • 22
  • 63
  • 74

3 Answers3

13

That is happening because you are using the keyCode member, for example, a lower case 'a' and an upper case 'A' have the same keyCode, because is the same key, but a different charCode because the resulting character is different.

To get the charCode, you should use the keypress event, and get the event.charCode member if available, otherwise, you get the event.keyCode which for IE, on the keypress event has the right information.

Give a look to the following example:

document.onkeypress = function (e) { 
  e = e || window.event; 
  var charCode = e.charCode || e.keyCode, 
      character = String.fromCharCode(charCode); 

  alert(character);
};
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • with this code: when I type "2" i get charCode 0; keyCode 50; character 2; when I type Shift-2 I get the same, but in my textbox the "@" appears. onkeypress event doesn't seem to know whether yoour Shift key is down.... – Michiel Feb 08 '13 at 10:23
2

just look at these solution similar to your requirement

and for keycode reference use this

and keycode is depend on browser check it

Community
  • 1
  • 1
ArK
  • 20,698
  • 67
  • 109
  • 136
1

you'll get character code in keypress event
try this out: http://www.w3.org/2002/09/tests/keys.html

They use following code to convert to character:

var charCode = (evt.charCode) ? evt.charCode : evt.keyCode;

this also may be helpful as keycodes reference

Niki Tonsky
  • 1,327
  • 11
  • 19