Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 318
OOProg Avatar asked Oct 22 '25 16:10

OOProg


1 Answers

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.

like image 98
Daniel Vassallo Avatar answered Oct 25 '25 07:10

Daniel Vassallo