JavaScript to Disable Form Submit with Enter Key

I ran into an issue the other day where I needed to disable form submission when the enter key was pressed. To fix this you need to add a hander for onKeyPress for the <body>. This will disable any effect by the Enter key for the entire page.

onKeyPress for the <body>. This will disable any effect by the Enter key for the entire page.

<script language="JavaScript">
function disableEnterKey(e)
{
     var key;
     if(window.event)
          key = window.event.keyCode;
     else
          key = e.which;
     return (key != 13);
}
</script>
<body onKeyPress="return disableEnterKey(event)">

If you want to disable form submission for a particular input field, add the onKeyPress handler of the input field:

<input type="text" name="foo" onKeyPress="return disableEnterKey(event)" >

]]>

Related Posts

Leave a Reply