Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable keyboard <enter> key [duplicate]

Tags:

javascript

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">

<head>
    <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>
</head>
<body onkeydown="TriggeredKey(this)">
like image 597
Cameron Avatar asked Aug 05 '09 20:08

Cameron


People also ask

How do I disable the enter key on my keyboard?

Disabling enter key for the form keyCode === 13 || e. which === 13) { e. preventDefault(); return false; } }); If you want to prevent Enter key for a specific textbox then use inline JS code.

Why is KeyCode deprecated?

KeyCode was deprecated because in practice it was “inconsistent across platforms and even the same implementation on different operating systems or using different localizations.” The new recommendation is to use key or code .


3 Answers

If you have jQuery, try this:

$('html').bind('keypress', function(e)
{
   if(e.keyCode == 13)
   {
      return false;
   }
});
like image 155
Tyler Carter Avatar answered Oct 22 '22 00:10

Tyler Carter


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

if (window.event.keyCode == 13 ) return false;
like image 22
Jason Musgrove Avatar answered Oct 21 '22 22:10

Jason Musgrove


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.

like image 2
C. Ross Avatar answered Oct 22 '22 00:10

C. Ross