Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if a character or number has been typed

Tags:

javascript

I would like to set up a home page where pressing any character (lowercase or uppercase) or any number redirects the user to the login page, as the home page itself doesn't have anything to do that requires typing.

My first attempt was this:

document.onkeyup = function() {
  document.location.href = "/login"
}

This works but it works for every key, including cursors, tab, and even caps lock. How can I restrict this function so it only responds to characters and numbers?

like image 992
sscirrus Avatar asked May 24 '11 21:05

sscirrus


People also ask

How do I check if a string is char or number?

We can check whether the given character in a string is a number/letter by using isDigit() method of Character class. The isDigit() method is a static method and determines if the specified character is a digit.

How do you check if a character is a number or letter in JavaScript?

To check if a character is a letter, call the test() method on the following regular expression - /^[a-zA-Z]+$/ . If the character is a letter, the test method will return true , otherwise false will be returned.

How do you check if a character is a letter or number in C?

C isalpha() The isalpha() function checks whether a character is an alphabet or not. In C programming, isalpha() function checks whether a character is an alphabet (a to z and A-Z) or not. If a character passed to isalpha() is an alphabet, it returns a non-zero integer, if not it returns 0.


1 Answers

When the event occurs, the key code is sent as an event argument. We can use that to determine if a character or number key was pressed. Like this:

document.onkeyup = function(e) {

  if ((e.keyCode >= 65 && e.keyCode <= 90) ||
      (e.keyCode >= 97 && e.keyCode <= 122) ||
      (e.keyCode >= 48 && e.keyCode <= 57)){
      document.location.href = "/login";
  }
};

For reference, the number used above are ASCII codes, you can find the complete list here: http://asciitable.com/. 48-57 are numbers 0-9, 65-90 are upper case characters, and 97-122 are lower case characters.

You can find a very simple JS Fiddle example here: http://jsfiddle.net/jpYyg/ . Remember to click inside the "Result" panel (bottom-right one) before pressing any buttons or it won't work!

HTH

like image 138
Karl Nicoll Avatar answered Sep 30 '22 15:09

Karl Nicoll