views:

373

answers:

3

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?

+3  A: 
if(event.keyCode >= 48 && event.keyCode <= 90) {
    //the key pressed was alphanumeric
}
Douwe Maan
+4  A: 

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.

Andy E
how do i check a 'backspace' with the dynamic check?
weng
I'm not sure. backspace is keyCode 8, so you could try `\u0008` inside the square brackets of the regex check.
Andy E
Note that this has to be done in the `keypress` event rather than the `keydown` event.
Tim Down
A: 

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:

document.onkeypress = function(evt) {
   evt = evt || window.event;
   var charCode = evt.which || evt.keyCode;
   var charStr = String.fromCharCode(charCode);
   if (/[a-z0-9]/i.test(charStr)) {
       alert("Letter or number typed");
   }
};

If you want to check for backspace, I'd use if (charCode == 8) {...}

Tim Down