The first time a keypress
event fires, it logs an empty input value even though the input has a value. The second time it logs the value but is one keystroke behind in comparison with the input's value. You can check this behavior on the next example:
document.addEventListener('DOMContentLoaded', () =>
{
const input = document.querySelector('input');
input.addEventListener('keypress', e =>
{
console.log(e.target.value);
});
});
<input type="text"/>
However, the next workaround makes it work, even though I pass in 0ms
.
document.addEventListener('DOMContentLoaded', () =>
{
const input = document.querySelector('input');
input.addEventListener('keypress', e =>
{
setTimeout(() => console.log(e.target.value), 0);
});
});
<input type="text"/>
Why is this hapenning?
The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt, Shift, Ctrl, or Meta.
The keypress () method triggers the keypress event, or attaches a function to run when a keypress event occurs. The keypress event is similar to the keydown event. The event occurs when a button is pressed down. However, the keypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC).
The keypress event is similar to the keydown event. The event occurs when a button is pressed down. However, the keypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC). Use the keydown() method to also check these keys.
The keypress () method triggers the keypress event, or attaches a function to run when a keypress event occurs. The keypress event is similar to the keydown event. The event occurs when a button is pressed down. However, the keypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC). Use the keydown () method to also check these keys.
When you press a key
for the first time, the value assigned to the input is empty
at the time the keypress
event takes place, then the character is added to the input, but a moment later. This same is valid for future keypress
events, the value of the input
you read is the previous before the input changes
. Also, if you read on the MDN there is a warning about keypress being dropped. Hence, and instead, you may want to listen on keyup
event as shown on the next example:
const input = document.querySelector('input');
input.addEventListener('keyup', e =>
{
console.log(e.target.value);
});
.as-console {background-color:black !important; color:lime;}
<input type="text" id="input">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With