I want to use an if-statement to run code only if the user types in a letter or a number.
I could use
if(event.keyCode == 48 || event.keyCode == 49 || event.keyCode == 50..) {
// run code
}
Is there an easier way to do this? Maybe some keycodes don't work in all web browsers?
Use
event.key
and modern JS!No number codes anymore. You can check key directly.
You could also use a simple regex.
^$
ensures 1 char,i
ignores caseor individually:
If you want to check a range of letters you can use greater than and less than:
For a more dynamic check, use a regular expression:
See the MDC documentation for the
keyCode
property, which explains the difference between that and thewhich
property and which events they apply to.Accept numbers or letters with javascript by Dynamic Process using regular Expression.
Add onkeypress Event for Specific Control
onkeypress="javascript:return isNumber(event)"
modified answer of @user4584103, allows us to remove characters, and navigate in input box and filter out every not num character
number validation, works fine for me
First, if you're doing this, make sure it's in the
keypress
event, which is the only event for which you can reliably obtain information about the character the user has typed. Then I'd use the approach Andy E suggested:If you want to check for backspace, I'd use the
keydown
event instead and check for akeyCode
of 8 because several browsers (including Chrome) do not fire akeypress
event for the backspace key.