Entry
How to cancel a keystroke before it is displayed in a text input box in NS6.
How to cancel a keystroke before it is displayed in a text input box in NS6.
How to cancel a keystroke before it is displayed in a text input box in NS6.
Jun 3rd, 2005 10:53
Loofa Sponge, Jim Fuqua,
It is difficult to cancel a keystroke in NS6. It is easy in IE. Here I
will only address NS6. There may be simpler and better ways, but I have
not found them.
It appears that once the keystroke is at the text input box it is too
late for preventDefault() to work on the event object.
I wrapped the text input box in a <div> </div> tag and captured the
event before it bubbled to the text input box. Here either cancelBubble
() or preventDefault() will work on the event object. preventDefault
will trap the tab key while cancelBubble will not.
Most posted solutions use "return false" which does not work with NS6.
[ return false works with the onkeypress event ]
This solution will work on the delete key to prevent deletion of
selected text. I have not tried the tab keys. The solution is listed
below. Check code for problems introduced by line wrapping if cutting
and pasting.
<html>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
// No effort made to accomodate any browser except NS6
function init() {
var myElement = document.getElementById("sampleDiv");
myElement.addEventListener("keypress", NS6_onKeypress, true);
}
function NS6_onKeypress(e)
{
alert("e.charCode=" + e.charCode);
e.preventDefault(); // must get keypress before it gets to
//input box "text1"
alert("e.cancelable="+e.cancelable);
alert("e.target.id="+e.target.id);
var phase;
switch (e.eventPhase)
{
case 1: phase="CAPTURING_PHASE ";break;
case 2: phase="AT_TARGET ";break;
case 3: phase="BUBBLING_PHASE ";break;
}
// to cancel input must be at CAPTURING_PHASE phase not AT_TARGET
alert("e.eventPhase="+phase);
alert("e.currentTarget.id="+e.currentTarget.id);
alert("e.type="+e.type);
alert("e.charCode=" + e.charCode);
}
</SCRIPT>
</HEAD>
<BODY onload="init()" >
<div id="sampleDiv" name="sampleDivName" style="position:absolute;
left:200px; top:100px;
width:600px; height:200px; background-color:#ff0000;
visibility:visible; clip:rect(0px 700px 100px 0px);">
<FORM name="myForm" >
<input type="text" id="text1" name="text1">
<input type="text" id="text2" name="text2">
</FORM>
</div>
</BODY>
</html>