ajsie ajsie - 5 months ago 37x
Javascript Question

detect numbers or letters with jquery/javascript?

i want to use an if-statement to run a 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

but is there an easier way to do this? maybe some keycodes dont 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.