Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  64] [ 7]  / answers: 1 / hits: 101570  / 15 Years ago, sat, february 13, 2010, 12:00:00

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?


More From » jquery

 Answers
15

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:


const input = String.fromCharCode(event.keyCode);

if (/[a-zA-Z0-9-_ ]/.test(input)) {
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.


[#97578] Wednesday, February 10, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sandra

Total Points: 708
Total Questions: 100
Total Answers: 84

Location: Bosnia and Herzegovina
Member since Thu, Jun 24, 2021
3 Years ago
sandra questions
Tue, Jun 30, 20, 00:00, 4 Years ago
Sun, May 31, 20, 00:00, 4 Years ago
Wed, May 20, 20, 00:00, 4 Years ago
Fri, May 31, 19, 00:00, 5 Years ago
;