...

View Full Version : Keypress event question



cgwalls
09-08-2008, 03:37 AM
Okay so I am pretty new to javascript and i am having troubles with the onkeypress event. I am trying to make it so when you press any key a variable goes up by 1 and then shows it in the browser. But i don't want it to write extra numbers every time. So say the variable is at 3 and you press a key i want the 3 to change to 4 rather then a 4 popping up next to the 3.

Here's what i have so far...

<html>
<head>
<title>Key Press Test</title>
<script type="text/javascript">
var a = 0
function add()
{
a += 1
document.write(a);
}
</script>
</head>
<body>
<script type="text/javascript">
document.onkeypress="add()"
</script>
</body>
</html>

I got this to work once when I put the onkeypress event in the body tag but then it only let my press the key once and then the page kept loading. So how would I go about fixing this code?

Philip M
09-08-2008, 08:39 AM
Naturally onkeypress will only work if the document or field is in focus.


<html>
<head>
<title>Key Press Test</title>
<script type="text/javascript">
var a = 0;
function add() {
a += 1;
document.getElementById("div1").innerHTML = a;
}

</script>
</head>

<body>
<input type = "text" name = "txt1" onkeypress="add()"><br>
<input type = "text" name = "txt2" onkeypress="add()"><br>
<div id = "div1"></div>
</body>
</html>

or if you want to use document.onkeypress:-



<html>
<head>
<title>Key Press Test</title>
<script type="text/javascript">
var a = 0;
function add() {
a += 1;
document.getElementById("div1").innerHTML = a;
}
document.onkeypress = add;
</script>
</head>

<body>
<input type = "text" name = "txt1" ><br>
<input type = "text" name = "txt2" ><br>
<div id = "div1"></div>
</body>
</html>


Quizmaster: In seafood on a restaurant menu, the French word "poisson" translates into English as what?
Contestant: Chicken

cgwalls
09-12-2008, 01:18 AM
thank you so much!!! also sorry it took so long to reply but i was just wondering if there was anyway to make the variable only go up once if your holding the key down so you have to keep tapping the key to make the variable to go up.

Philip M
09-12-2008, 11:28 AM
document.onkeyup = add;

valcarni
10-05-2008, 06:47 AM
my question is quite similar to the one before. I wanna be able to trap the keypress 33 and 34 (page up and page down) within a webpage. If keypress 33 is done i want it to go to one url... and if keypress 34 is pressed to go to the other url.

Thank you.

valcarni
10-05-2008, 06:54 AM
<html>
<head>
<title>Key Press Test</title>
<script type="text/javascript">
function pageup() {
pageup.htm
}
function pagedown() {
pagedown.htm
}
document.onkeypress(33) = pageup;
document.onkeypress(34) = pagedown;
</script>
</head>

<body>

<div id = "div1"></div>
</body>
</html>


that's what i got so far and totally doesn't work... i haven't tried doing anything in years.. can ya tell :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum