PDA

View Full Version : Onkeypress for cursor key



rhodarose
11-08-2010, 08:18 AM
Good day!

In my javascript code I have a function for the enter key. I want to add cursor key in that function/ I research about the coding for cursor key but I can't find the code same on what I want to happen.

Here is the code:


<script language="javascript">
function handleEnter(e, nextfield)
{
var characterCode = (e && e.which)? e.which: e.keyCode;
if(characterCode == 13)
{
document.getElementById(nextfield).focus();
return false;
}
else
{
return true;
}
}
</script>
<input type='text' name='plt' onkeypress='return handleEnter(event,\"b0\");' />


Thank you

jscheuer1
11-08-2010, 11:51 AM
Use onkeydown. It's more reliable. The event.which isn't required by any modern browser (all Firefox, all IE, etc.).

I'm not certain what key you mean. To determine the code you're looking for do:


<input type="text" onkeydown="alert(event.keyCode);">

and hit that key while in that text input.

Then in your function (say the code is 93 - what I suspect you're after, though even this may vary system to system):


<script type="text/javascript">
function handleEnter(e, nextfield){
var characterCode = e.keyCode;
if(characterCode === 13 || characterCode === 93){
document.getElementById(nextfield).focus();
return false;
} else {
return true;
}
}
</script>

Or, if the result from that key is desired to be different from the enter key's:


<script type="text/javascript">
function handleEnter(e, nextfield){
var characterCode = e.keyCode;
if(characterCode === 13){
document.getElementById(nextfield).focus();
return false;
} else if(characterCode === 93) {
// Do some other stuff here,
// should include a return value of true or false to be consistent.
} else {
return true;
}
}
</script>

Notes:


The code may as I say vary.

Taking control over any key is risky as any given system may override that and/or still also provide the default action regardless of the function you assign to it.

Taking control in this manner is against w3c recommendations as it may frustrate the user or worse, degrading accessibility of the page for certain handicap setups and older software/hardware.