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?
If you want to check a range of letters you can use greater than and less than:
if (event.keyCode >= 48 && event.keyCode <= 57) alert("input was 0-9"); if (event.keyCode >= 65 && event.keyCode <= 90) alert("input was a-z");
For a more dynamic check, use a regular expression:
var inp = String.fromCharCode(event.keyCode); if (/[a-zA-Z0-9-_ ]/.test(inp)) alert("input was a letter, number, hyphen, underscore or space");
See the MDC documentation for the keyCode
property, which explains the difference between that and the which
property and which events they apply to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With