PDA

View Full Version : Catching the escape key in a form


spib
08-13-2002, 11:08 AM
Hi,

I'm using IE6 and when I hit the escape key in a textarea, I get a warning that the form will be reset. If I then hit cancel, the form is still reset (it is reset as soon as the escape key is pressed).

What I want to do is override IE's messagebox here and display my own. I have tried the following code which catches the escape key but doesn't cancel the event bubble.

function KeyPress()
{
if (window.event.keyCode == 27)
{
// User pressed escape in the form
window.event.cancelBubble = true;
window.alert("Cancelled Bubble");
return true;
}
}

<form onkeydown="KeyPress()">
...


Anyone have any clues on what I'm doing wrong here?

Cheers

James

beetle
08-13-2002, 03:05 PM
Cancelling the bubbling has nothing to do with the event occurance. Bubbling just stops the event from firing on any of the node's children, but it has obviously already fired once because your function is running. You need to return a false value from the function to cancel it.function KeyPress()
{
if (window.event.keyCode == 27)
return false;
}

spib
08-13-2002, 03:10 PM
Thanks for the reply. Unfortunately that didn't work. My function was called and I returned false, but IE still reset the form and displayed the messagebox.

Do you have any other suggestions?

Cheers

James

beetle
08-13-2002, 03:34 PM
Oop. Sorry...wasn't looking that close. You need onKeyDown instead of onKeyPress. onKeyPress fires AFTER the default action of the key. onKeyDown fires BEFORE the default action of the key. However, I should note that onKeyDown cannot be cancelled in IE4.

spib
08-13-2002, 03:42 PM
Actually, I am hooking OnKeyDown as the code shows.

Turns out that it wasn't that which was the problem. In the code, I am hooking the onkeydown for the form. If I change it to hook the OnKeyDown for the whole document it works

if (document.all)
{
document.onkeydown = CheckKeyPress ;
}

function CheckKeyPress()
{
if(window.event.keyCode == 27)
{
window.alert("Caught it");
return false;
}
}

Cheers for the help

James

beetle
08-13-2002, 03:49 PM
Hrm. Strange. onKeyDown worked on the form for me. May be a browser difference.