tags:

views:

418

answers:

3

I just want to disable the "enter" key on the keyboard. The following script locks the whole keyboard down for some reason except for still allowing only the "enter" key to be used.

If this helps pinpoint what's missing or wrong, I'm using V.S. 2005, VB.NET 2.0, and I.E. 7.

<meta http-equiv="content-type" content="text/html; charset=windows-1252">

<script language="JavaScript">
function TriggeredKey(e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
if (window.event.keyCode = 13 ) return false;
}
</script>

<body onkeydown="TriggeredKey(this)">
+2  A: 

If you have jQuery, try this:

$('html').bind('keypress', function(e)
{
   if(e.keyCode == 13)
   {
      return false;
   }
});
Chacha102
Or you can fix your code with Jason's answer. I just prefer jQuery.
Chacha102
Thanks for the alternative option.
Cameron
+11  A: 

Your = should probably be an == (comparison vs. assignment)

if (window.event.keyCode == 13 ) return false;
Jason Musgrove
Good catch, I missed that one!
C. Ross
I've tried this also and the enter button is still not disabled, although the rest of the keyboard is usable whereas most keys were locked before. Could there be an unknown network setting that's creating this incompatibility? I'm unfamiliar with JavaScript, but this seems like it should be simple and straightforward.
Cameron
+1  A: 

I've used this code successfully.

function handleKeypress(e){

    e = e || window.event ;
    if (e == null){
        return false;
    }

    if (e.keycode == 13){
        CompleteEvent(e);
    }
}

function CompleteEvent(e){
    e.cancelBubble = true;
    e.returnValue = false;
}

Also I highly recommend using the new form of hook setting for javascript.

function setKeyHook()
{     
    var eventName = 'onkeydown';
    var handlerFunc = handleKeypress;


    body.detachEvent( eventName, handlerFunc );              

    body.attachEvent( eventName, handlerFunc );

}

onload = setKeyHook;

Good luck.

See this question for more information than you wanted. Kudos to Peter Bailey for teaching me.

C. Ross
While I couldn't get this to work yet either, is there a missing { tag? Thanks for the code! I'll keep playing with this. It seems as if something else in my code or environment isn't playing nice.
Cameron
Yes there was. I've now fixed it. Sorry about that.
C. Ross