PDA

View Full Version : Keypress Event in JavaScript


Deepali
11-10-2005, 06:58 AM
I use the keypress event for tracing the keypress events.

The code is running very nicely in IE, but it will give an error in firefox and also not working properly. I block the specific keys in that and if we type the blocked keywords, that won't type in the text box.

The code I written is --

if ((event.keyCode < 65 ¦¦ event.keyCode > 90) && (event.keyCode < 97 ¦¦ event.keyCode > 122))
event.returnValue = false;

but firefox gives error for the event object I used in this code.

What is the other way to do this?

Thanks in advance.

Kor
11-10-2005, 09:49 AM
I have not decided if a bug (and whose bug is it) but it seems like Moz has different behaviors according to the different key events. The best you can do is to use onkeyup fo Mozilla and onkeypress for IE.

Even so, Moz will not return the corect keycodes for special characters. If you need only usual characters, than use onkeyup for Moz.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Captura key code</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
function capturekey(e){
var key=(typeof event!='undefined')?window.event.keyCode:e.keyCode;
alert('keycode : '+key);
}
if(navigator.appName!= "Mozilla"){document.onkeyup=capturekey}
else{document.addEventListener("keypress",capturekey,true);}
</script>
</head>
<body>
</body>
</html>

Kor
11-10-2005, 09:51 AM
Due to this, maybe it will a better ideea to use Regular Expresion validate function instead of key capture to prevent some characters on input.

Deepali
11-18-2005, 07:46 AM
But this will give me error in Mozilla -
The Error Message is -
Error: uncaught exception: [Exception... "Component returned failure code: 0x8000ffff (NS_ERROR_UNEXPECTED) [nsIDOMTreeWalker.nextNode]" nsresult: "0x8000ffff (NS_ERROR_UNEXPECTED)" location: "JS frame :: chrome://global/content/bindings/button.xml :: fireAccessKeyButton :: line 93" data: no]


I have not decided if a bug (and whose bug is it) but it seems like Moz has different behaviors according to the different key events. The best you can do is to use onkeyup fo Mozilla and onkeypress for IE.

Even so, Moz will not return the corect keycodes for special characters. If you need only usual characters, than use onkeyup for Moz.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Captura key code</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
function capturekey(e){
var key=(typeof event!='undefined')?window.event.keyCode:e.keyCode;
alert('keycode : '+key);
}
if(navigator.appName!= "Mozilla"){document.onkeyup=capturekey}
else{document.addEventListener("keypress",capturekey,true);}
</script>
</head>
<body>
</body>
</html>

liorean
11-18-2005, 08:18 AM
I have not decided if a bug (and whose bug is it) but it seems like Moz has different behaviors according to the different key events. The best you can do is to use onkeyup fo Mozilla and onkeypress for IE.It's not a bug. It's very much intended.

The keydown/-up events are triggered when the key is pressed down and when it is released respectively but will not trigger while the button is held down. The keyCode property will tell you which key is being pressed down or released (ie. it will not be affected by mods such as caps lock or the shift key). They will trigger for any keys.

The keypress event is triggered when a character is entered by keyboard. It will trigger for each entry, including repetition by holding the key down. The charCode property will tell you which character is entered (ie. it will return the character entered, after modifications). It will trigger for any character entry, but not for any other key presses. Keys for text navigation (eg. arrow keys, home, end etc.) will trigger a keypress event which has a keyCode instead of a charCode property set, because of their special meaning for character entry.


Moz is the browser behaving correctly here. Iew and op instead use only the keyCode property (so when you would read the charCode property in moz, you read keyCode in iew and op). Iew doesn't trigger a keypress event for text navigation. Opera does trigger a keypress event for text navigation.

The idea is that keyCode should never return a modified key code - Shift-E and E should return the same keyCode. On the other hand, charCode should always return the character entered, and always be after modificator keys. This is the reason moz decided to do away with the old which property of nn4, which behaved just like keyCode does in iew.


See <uri:http://www.din.or.jp/~hagi3/JavaScript/JSTips/Mozilla/Samples/KeyEvent.htm> for a good page to test the way various browsers work.

Kor
11-18-2005, 08:21 AM
I see no errors. Tested with Mozilla 1.6, Firefox 1.0.4, IE6, NS7.1 on Win2000.

---
Thanks liorean. That make sense, indeed.

Deepali
11-18-2005, 08:53 AM
but this code gives me error in NS 8.0
The Error is -
Error: [Exception... "'Permission denied to get property XULElement.selectedIndex' when calling method: [nsIAutoCompletePopup::selectedIndex]" nsresult: "0x8057001e (NS_ERROR_XPC_JS_THREW_STRING)" location: "JS frame :: file:///f:/Deepali/TMP94nh5q570n.htm :: capturekey :: line 11" data: no]
Source File: file:///f:/Deepali/TMP94nh5q570n.htm
Line: 11

what type of error it is?
How to overcome this error?
Please help me as early as possible.

I see no errors. Tested with Mozilla 1.6, Firefox 1.0.4, IE6, NS7.1 on Win2000.

---
Thanks liorean. That make sense, indeed.

Kor
11-18-2005, 08:57 AM
I don't know. Maybe is NS 8 bug, or maybe the detector code is not a proper one for NS8...

By the way, I don't know why Gecko launched NS8 when Moz and especially FF are such good browsers...:)

Deepali
11-18-2005, 09:03 AM
Thanks a lot Kor for your suggestion and help.
It is working for other browsers.
I will find out the solution for NS8..
Thank you again.:thumbsup:

I don't know. Maybe is NS 8 bug, or maybe the detector code is not a proper one for NS8...

By the way, I don't know why Gecko launched NS8 when Moz and especially FF are such good browsers...:)

glenngv
11-18-2005, 09:08 AM
That is a Moz bug. The fix for that is to turn autocomplete off.
<input type="text" autocomplete="off" />

Deepali
11-19-2005, 06:34 AM
I have got the solution for the problem. It is working on all the browsers.
This code could be helpful for you all, hence I am posting this with code below---


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us">
<head>
<title>allow only number input</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<style type="text/css">
/*<![CDATA[*/
html {
background: #fff;
color: #000;
font-size: 1em;
}
body {
margin: 0;
padding: 8px;
}
form {
margin: 0;
padding: 5px;
}
/*]]>*/
</style>
<script type="text/javascript">
//<![CDATA[

// Cross-browser event listener
function listenForEventIn(obj,type,func,bubble)
{
if (obj.addEventListener)
{
obj.addEventListener(type,func,bubble); // For Presto and Gecko
}
else if ( obj.attachEvent )
{
obj.attachEvent("on" + type, func); // For Trident
}
}

// Window.onload
listenForEventIn(window,"load", function()
{
var n = document.getElementById("nums");
n.value = "";
n.focus();
function check(e)
{
var k;
if (e.charCode)
{
k = e.charCode; // For Gecko
}
else if (e.keyCode)
{
k = e.keyCode; // For Presto
}
if ( k != 37 && k != 38 && k != 39 && k != 40 && k != 35 && k != 46 && k != 8 && k != 36)
{
if ( k < 47 || k > 57 )
{
if ( e.preventDefault )
{
e.preventDefault(); // For Presto and Gecko
}
else
{
return false; // For Trident
}
}
}
}
if (window.addEventListener)
{
listenForEventIn(n, "keypress", check, false); // For Presto and Gecko
}
else
{
listenForEventIn(n, "keydown", check, false); // For Trident
}

listenForEventIn(document.getElementById("submit"), "click", function(e) {
if (n.value == "")
{
if (e.preventDefault)
{
e.preventDefault(); // For Presto and Gecko
}
else
{
// For Trident
alert("box cannot be empty");
n.focus();
return false;
}
alert("box cannot be empty");
n.focus();
}
}, false);

}, false);
//]]>
</script>
</head>
<body>
<form action="http://www.google.com/search?q=" method="get"><div><input type="text" id="nums" /><input type="submit" value="submit" id="submit" /></div></form>
<div>Click submit when box is empty</div>
</body>
</html>

Thanks a lot again for your help.

MemtechLodhi
09-20-2011, 03:19 PM
Hello Everyone,
onkeypress event is called when ever any key is pressed in control. Normally we use onkeypress event to check that which key is pressed by user or when we want to make key logger type application..... please check out the following links for more details.....
http://mindstick.com/Articles/606dc00b-0f5b-4d5e-ad7b-174b6cb33423/?Implementing%20onkeypress%20event%20in%20Java%20Script

:thumbsup:Thanks !!!!

Kor
09-20-2011, 03:32 PM
Hello Everyone,
onkeypress event is called when ever any key is pressed in control. Normally we use onkeypress event to check that which key is pressed by user or when we want to make key logger type application..... please check out the following links for more details.....
http://mindstick.com/Articles/606dc00b-0f5b-4d5e-ad7b-174b6cb33423/?Implementing%20onkeypress%20event%20in%20Java%20Script

:thumbsup:Thanks !!!!
It is not so simple. A lot of events are incomplete, incorrect or bugged implemented in different browsers, so that they might return unexpected results. onkeypress is one of them. See also:
http://www.quirksmode.org/dom/events/index.html
http://www.quirksmode.org/js/keys.html

In your example you should have simply used onkeyup instead of onkeypress, to avoid any cross-browser problem.