Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the value of each key pressed and use it in a variable with jQuery?

How do I get the value of each key pressed and use it in a variable with jQuery? I want to get a key pressed and reveal a certain picture on the page that correlates to that key right when it is pressed. I also ONLY want to target A-Z and "."

Thanks!

like image 459
Michael Rader Avatar asked Nov 22 '11 05:11

Michael Rader


People also ask

How does jQuery detect keyboard press?

jQuery | keypress() The keypress() method in jQuery triggers the keypress event whenever browser registers a keyboard input. So, Using keypress() method it can be detected if any key is pressed or not.

What is Keyup and Keydown in jQuery?

jQuery keyup() Method The order of events related to the keyup event: keydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.

How do you check if Enter key is pressed in JavaScript?

And the following JavaScript code to detect whether the Enter key is pressed: const input = document. querySelector("input"); input. addEventListener("keyup", (event) => { if (event.

Is Onkeypress deprecated?

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.


1 Answers

Using jQuery, you can use the keypress event, and then convert the character to a string, and match it against your criteria.

Here's a working example:

$(document).keypress(function(e)
{
    var s = String.fromCharCode(e.which);
    if (s.match(/[a-zA-Z\.]/))
        console.log(s + ' is a match!');
});

Update: For the key pressed inside another element, just use the selector $('#LearnStart'), as seen here.

like image 76
wsanville Avatar answered Oct 10 '22 02:10

wsanville