How to get the key pressed and put into array in JavaScript?

15,206

Solution 1

What about something like this?

var your_array = [];

document.onkeydown = function (e) {
  var keyPress;

  if (typeof event !== 'undefined') {
    keyPress = event.keyCode;
  }
  else if (e) {
    keyPress = e.which;
  }

  your_array.push(String.fromCharCode(keyPress));

  return false;   // Prevents the default action
};

UPDATE: If you require accurate character information (such as, the distinction of uppercase from lowercase, and other things), make sure to check out @Tim Down's comments below and his other answer.

Solution 2

You need the keypress event for this. keydown and keyup cannot be used reliably to get character information. An excellent and detailed explanation of JavaScript key events is at http://unixpapa.com/js/key.html

var charsTyped = [];

document.onkeypress = function(evt) {
    evt = evt || window.event;

    // Ensure we only handle printable keys
    var charCode = typeof evt.which == "number" ? evt.which : evt.keyCode;

    if (charCode) {
        charsTyped.push(String.fromCharCode(charCode));
    }
};

Solution 3

Daniel's answer is perfect, but if you want to get the actual character (not the numerical code), you can use this function:

String.fromCharCode(code);

See MDN for more info.

Share:
15,206
OOProg
Author by

OOProg

Updated on June 05, 2022

Comments

  • OOProg
    OOProg almost 2 years

    How do I get the key that was pressed and, instead of returning the key code, put that key into an array?

    For example, the user will press 'a'. Then, the code will put 'a' - not the keycode for the character - into an array.

    Thanks in advance!