Forum Moderators: open
This works great in Firefox and IE, however in Safari, it calls the function twice (or appears to) when you hit the up or down arrow key, so it ends up adding or subtracting 2 from the quantity value in the box. I figured this out by putting
alert(keyCode) in my function. It alerts twice every time you hit a key. onkeyup seems to be the best cross-browser solution for this, because I have also discovered that if you use onkeydown or onkeypress, Safari registers a different keyCode (38 is up, 40 is down...it was registering 65233 and 65232!). Anyway, if anyone has any tips, it would be very helpful. While my client probably won't use Safari, there is a chance that they will...also, I'm just curious about why this is occuring.
Thanks!
Here is the function:
function toggleQuantity(element,event)
{
var keyCode = event.keyCode;
if (keyCode == 38)
{
element.value = parseInt(element.value) + 1;
}
if (keyCode == 40)
{
element.value = element.value-1;
}
}
And I call it like this:
<input type="text" onkeyup="toggleQuantity(this,event);" />
If Safari is implementing onkeyup, it is likely a recent feature and perhaps not one that can be relied upon, yet.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Key Events</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<style type="text/css">
td,th{border:2px solid #aaa;}
</style>
<script type="text/javascript">
var t_cel,tc_ln;
if(document.addEventListener){ //code for Moz
document.addEventListener("keydown",keyCapt,false);
document.addEventListener("keyup",keyCapt,false);
document.addEventListener("keypress",keyCapt,false);
}else{
document.attachEvent("onkeydown",keyCapt); //code for IE
document.attachEvent("onkeyup",keyCapt);
document.attachEvent("onkeypress",keyCapt);
}
function keyCapt(e){
if(typeof window.event!="undefined"){
e=window.event;//code for IE
}
if(e.type=="keydown"){
t_cel[0].innerHTML=e.keyCode;
t_cel[3].innerHTML=e.charCode;
}else if(e.type=="keyup"){
t_cel[1].innerHTML=e.keyCode;
t_cel[4].innerHTML=e.charCode;
}else if(e.type=="keypress"){
t_cel[2].innerHTML=e.keyCode;
t_cel[5].innerHTML=e.charCode;
}
}
window.onload=function(){
t_cel=document.getElementById("tblOne").getElementsByTagName("td");
tc_ln=t_cel.length;
}
</script>
</head>
<body>
<table id="tblOne">
<tr>
<th style="border:none;"></th><th>onkeydown</th><th>onkeyup</th><th>onkeypress</td>
</tr>
<tr>
<th>keyCode</th><td> </td><td> </td><td> </td>
</tr>
<tr>
<th>charCode</th><td> </td><td> </td><td> </td>
</tr>
</table>
<button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML=' '};">CLEAR</button>
</body>
</html>