Javascript String.fromCharCode Case Sensitivity?

Joel Blum picture Joel Blum · Feb 18, 2013 · Viewed 9.2k times · Source

I am simply listening for a keyup event of an input element and gather the results into a string like so

word=word+String.fromCharCode(key.keyCode);

The problem is that the word is in capital letters while I want it to be case-sensitive. For example if I type abcef my accumulated word becomes 'ABCEF' .

Note - I need a pure javascript solution (no libraries..) Any thoughts?

Answer

adeneo picture adeneo · Feb 18, 2013

Events like keyup and keydown will return 65 for both a and A (and also true for event.shiftKey if that key is held down).

The keypress event returns different keycodes for upper and lower case letters, so to get this working case sensitive you should use the keypress event, and fromCharCode() will return the correct letter, case sensitive.