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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With