PDA

View Full Version : Resolved Checking Users keyboard input



keyboard
01-24-2012, 04:16 AM
Hello everyone, found this script on the net (I've made some changes)



<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript1.2">
<!--
function IEKeyCap()
{
if (window.event.keyCode == 72)
{
alert('That\'s the H key');
var myNum = 1;
}



if(myNum == 1){
if (window.event.keyCode == 105)
{
alert('That\'s the i key');
}


}
}
//-->
</SCRIPT>
</HEAD>
<BODY onKeyPress="IEKeyCap()">
</BODY>
</HTML>


I want it so that the user has to enter "Hi" for something to happen. It dosen't have to be secure and it only has to work in IE.
When I type "H" it comes up the message That's the H key, but after that when I enter I, nothing happens. Any help?

djr33
01-24-2012, 04:54 AM
You're creating two separates instances of the function, so the variable's value isn't stored between them.
The solution is to use a global scope variable.


<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript1.2">
<!--
var myNum=0; //start as global var with default of 0
function IEKeyCap()
{
if (window.event.keyCode == 72)
{
alert('That\'s the H key');
myNum = 1; //store value of 1 for later in the global var
}



if(myNum == 1){
if (window.event.keyCode == 105)
{
alert('That\'s the i key');
myNum = 0; //reset
}


}
}
//-->
</SCRIPT>
</HEAD>
<BODY onKeyPress="IEKeyCap()">
</BODY>
</HTML>
That may not be necessarily the cleanest way to do it, but it should work.

Note: there's no reason this can't work in all/most browsers. Some browsers have slightly different ways to get the keys (and for some special keys might even have different codes), but if you end up needing a cross-browser version, it's possible, and there's plenty of information out there if you search for it.


Another, more general way to do this would be to skip the first if statement and just store the key as a var lastkey. Then on each loop, check both the current key (like you're doing now) and also check the value of lastkey. That's easier than embedding a bunch of if statements and placeholder variables (like myNum).

keyboard
01-25-2012, 02:17 AM
Thanks djr33