简体   繁体   中英

How do I get the character pressed in a textarea

This is really weird.

I have a textarea. I listen to the keyup and keypress events.

When I press "(", keypress is fired with e.keyCode == e.which == 40

When I press the arrow down key, keyup is fired with e.keyCode == e.which == 40

Why is this so strange?

Traditionally, the arrow keys overlapped ASCII codes, but were represented to the programmer as a two-byte sequence so you were aware that a special key has been pressed. With the advent of Unicode this is no longer a clean solution.

Browsers have implemented different ways of representing special key input to the Javascript runtime. The details are explained here .

I usually use the 'keydown' event when detecting arrow keys, as this event has the correct keycode attached and will fire with a different keycode(the one for 9) when the user is typing a left parenthesis. This may not work in cases where you want to allow the user to repeat the keyed event by holding down the arrow key.

keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

Char code for "(" is 40 ( keypress event) and key code for down arrow is also 40 ( keyup ).

Try:

String.fromCharCode(40); // "("

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