简体   繁体   中英

Why does keyup event has different key property for same input?

I need to detect when input value changes and if the last character entered is '@' I need to edit this input in some way.

So I added event listener for keyup event.

const inputEl = document.getElementById('input');

inputEl.addEventListener('keyup', event => {
    console.log(event.key);
})

This will sometimes log 'Shift' and '@' and sometimes 'Shift' and '2' for the same value entered (@)

在此处输入图像描述

If I add this listener to keypress event instead, it always logs 'Shift' and then '@'.

But I cannot use keypress because this event fires before keyup and before input value is updated in the DOM.

Is there a way to detect last entered character in a reliable way?

You want to know "if the last character entered is '@'" so I would not use event.key for that as long as it triggers every key you press on your keyboard while you are focused in the input.

You should work with event.target.value and split the last character. Something like this:

 const inputEl = document.getElementById('input'); inputEl.addEventListener('keyup', event => { const value = event.target.value; console.log(value.substr(value.length - 1)); })
 <input id="input"/>

Just note that it will fire listener with every key you press even if it won't write anything (like shift ).

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