Michael Rader
Michael Rader

Reputation: 5957

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!

Upvotes: 5

Views: 9151

Answers (3)

wsanville
wsanville

Reputation: 37516

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.

Upvotes: 7

Baz1nga
Baz1nga

Reputation: 15579

avoid having ids preceeding with #. with an input of id LearnStar you can insert a script like this:

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

The live event basically takes care of the fact that if the control is rendered on the page after the script has been loaded.

You can do nifty stuff with this like prevent the user from typing non valid keys by using e.preventDefault() and returning false from the callback function.

Upvotes: 0

wargodz009
wargodz009

Reputation: 305

heres a link for jquery Keypress function and how to use it

Upvotes: 0

Related Questions