How to save to a variable what is typed on the screen

Asked

Viewed 86 times

6

I have a web page, and sometimes users press some numbers.

However, I have a Reader by usb, I while reading a code it shows me automatically 7 numbers, as if I had typed them on the web page.

How do I save these 7 numbers that are "typed" immediately on the web page, without input, with javascript?

1 answer

6


One option is to put one Listener in the document and store in an array the values pressed (or keyCodes) and do a continuous search in that array to check if what it has is what you’re looking for - or even store only what you want based on the keycode:

document.addEventListener("keydown", keyDownPress, false);
var valoresDigitados = [];

function keyDownPress(e) {
  var keyCode = e.keyCode;
  valoresDigitados.push(String.fromCharCode(keyCode));
}

function verValores(){
 console.log(valoresDigitados.join(""));
}
<button onclick="verValores()">Ver valores</button>

  • It is exactly, what I want, however, appears to me separate values "4","2","7","6", how do I get everyone together in the way: "4276"? Thank you.

  • I put a Join to join the array values, @Gonçalo

  • Thank you, this is what I was looking for, by the way, how do I put it in my document, because I put it and I can’t. How do I do the structure? I first put the <script> and the code or only after html?

  • I edited my question, the way I put the script.

  • I trust you’ll have no problem putting head by not manipulating any element that has not yet been created.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.