Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect numbers or letters with jQuery/JavaScript?

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?

like image 593
ajsie Avatar asked Feb 13 '10 09:02

ajsie


1 Answers

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.

like image 90
Andy E Avatar answered Sep 21 '22 09:09

Andy E