JS: Recognize dot or delete in keypress
Solution 1
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.
Solution 2
Use modern JS!
Use event.key === "." || event.key === "Delete"
, rather than arbitrary number codes!
Solution 3
it's only allow dot and numbers
const charCode = (event.which) ? event.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode!=46 ) {
return false;
}
return true;
Related videos on Youtube
Florian Müller
'bout me: florianmueller.me Come join the dark side: previon.swiss
Updated on June 15, 2022Comments
-
Florian Müller about 2 years
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!
-
Florian Müller about 13 yearsThanks ;) I found after a bit googling a little code snippet which is works on every browser ;) Thanx for the link :D function Tastendruck (Ereignis) { if (!Ereignis) Ereignis = window.event var key = Ereignis.keyCode || Ereignis.which; alert(key); } document.onkeyup = Tastendruck;
-
Merritt over 11 yearskeyboard period = 46 for me.
-
Ayyash almost 11 yearson keypress, e.which return 46 for both delete and dot :/
-
David R. almost 10 years@Ayyash not quite. Delete does not invoke onkeypress event, only onkeydown and onkeyup. The keyboard period onkeydown event code is 190.
-
Wirone almost 9 years@DavidR. you're not right.
delete
DOES invoke onkeypress event in Firefox. I got an issue with this few days ago when I wanted to prevent inputting chars different than[0-9,\.]
(onkeypress) with autonormalizing to only one dot (onkeyup with positive lookahead regex). -
David R. almost 9 years@Wirone good call. These are browser specific, so you'll need to check for Chrome, Firefox, IE, Edge, Safari, Opera, and then know what to do if another browser is being used.