简体   繁体   中英

How can I know what the value of the <input/> will be on keypressed?

I have an event listener on the "keypress" event:

input.addEventListener("keydown", function(e) {... }

When I read the value of the input field, it is not updated yet. Is there a way to know what the value of the input will be before waiting for the "keyup" event?

Note: I tried to use a setTimeout(function() {... }, 1); but it doesn't work with copy/paste (the input value is not updated). when I set the timeout to 10ms it does work in my tests but it doesn't feel like a robust solution (may depend on the speed of the hardware).

Perhaps a more robust solution will be to listen to the input event? However, this will not capture all keyboard events that will not change/mutate the value of the input (eg pressing the Home / End button):

 document.querySelector('input').addEventListener('input', (e) => { console.log(e.target.value); });
 <input type="text" />

Alternatively, if you really want to depend on keyboard events, then keyup is the event you want to listen to, since it is fired after the key has been lifted:

 document.querySelector('input').addEventListener('keyup', (e) => { console.log(e.target.value); });
 <input type="text" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM