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?
keypress
event is deprecated and should no longer be used. – Cornute