Problem when using keydown

Asked

Viewed 33 times

0

I’m doing a project that calculates some physics equations from the data passed by the user. My goal is that the program, when perceiving a "keydown", use the entered value to, if possible, calculate the result automatically, without the user having to click on any button to calculate.

The problem is that when it identifies the keydown, it first performs everything that was passed in the onkeydown function, and then generates the value. To be clearer follow an example:

const a = document.getElementById("a") // "a" é uma lacuna em que o user pode digitar
a.onkeydown = () => { 
var valor = a.value // valor do digito que o usuário digitou
alert(valor)
}

What happens is that it first does all the code I passed in "a. onkeydown" and then appears in the gap what the user typed. That is, if the user enters, for example, the number 2, the value variable will not receive anything, because at that moment the gap (a.value) is empty. So, if soon after the 2, he type 0 (forming the number 20), the value will receive the number 2, which was already typed.

I wanted that, before executing the code, it first received the value passed by the user, so that it could calculate in real time. Does anyone know any alternative?

1 answer

0

onkeydown is executed when the key is pressed, but has not yet been released by the user, that is, the value has not yet been entered in the input (read that answer for more details).

onkeyup is executed when the key is released, and the value has already been entered in the input.

Change your event from keydown for keyup:

const a = document.getElementById("a")

a.onkeyup = () => { 
  alert(a.value)
}
<input type="text" id="a" />

Browser other questions tagged

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