0

I have char, for example

var char = 'a'

I need to know values of both keyCode(65) and charCode(97). I know how to get charCode value 97.

'a'.charCodeAt(0)

How to get keyCode value? Simple subtraction - 32 do not work for fe 'A'. I know that I can have array of these values and search in them, but this seems a little overkill for me. Any other way ?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Petr Krčmárik
  • 221
  • 1
  • 2
  • 13
  • I believe the only way is from a key event or build your own object or array that will give you the value. There is no javascript function that just gives you key codes. – AtheistP3ace Oct 18 '15 at 18:14
  • "The only event from which you can reliably obtain character information (as opposed to key code information) is the keypress event." This link may help you out: http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion. You also may want to take advantage of `String.fromCharCode` (`String.fromCharCode('65') === 'a'`) – Gershom Maes Oct 18 '15 at 18:29

1 Answers1

0

Look this:

You can use the charCodeAt function to achieve this.

Working demo

function showKeyCode()
{
    var character = document.getElementById ( "character" ).value.substring(0,1);
    var code = document.getElementById ( "character" ).value.charCodeAt(0);
    var msg = "The Key Code for the \""+character+"\" character is "+code+".";
    alert(msg);
}
</script>


<input type="text" id="character" size="15">
<input type="button" value="Show Key Code" onclick="showKeyCode();">
Emir Marques
  • 2,603
  • 2
  • 16
  • 22