Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: Recognize dot or delete in keypress

I'd like to execute some code if the user presses the dot (on standard keybord or on numblock). But if I take it over Keycode (110), this is the same like the delete button.

How do I recognize them?

Thanks for your help!

like image 574
Florian Müller Avatar asked May 09 '11 18:05

Florian Müller


People also ask

How do I use the keypress () method in JavaScript?

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.

What is a keypress event in JavaScript?

Definition and Usage. 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).

Can I use the keypress event to capture non-printing keys?

You shouldn't use the keypress event, but the keyup or keydown event because the keypress event is intended for real (printable) characters. keydown is handled at a lower level so it will capture all nonprinting keys like delete and enter. Show activity on this post. Source: javascript char codes key codes from www.cambiaresearch.com

Why can't I Capture the Alt key event with a keypress?

The keydown event has the maximum coverage of keys to produce the contextual information. The keypress event works only for a subset of the keys. You can't capture the Alt, Ctrl, Shift, Meta, and other similar key events with a keypress. This also means that we can not fire the keypress event with key combinations like Ctrl Z, Shift Tab, and so on.


2 Answers

Delete key (usually above arrows) is 46, numpad decimal is 110, and the keyboard period is 190.

This is a pretty good page to know what keycodes are what: http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx

If this doesn't answer your question, please rephrase it as it's a little confusing what you are looking for.

like image 118
invertedSpear Avatar answered Oct 03 '22 19:10

invertedSpear


Use modern JS!

Use event.key === "." || event.key === "Delete", rather than arbitrary number codes!

like image 45
Gibolt Avatar answered Oct 03 '22 18:10

Gibolt