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.

<script language="JavaScript">

function disableEnterKey(e)
     var key;     
          key = window.event.keyCode;
          key = e.which;

     return (key != 13);

<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)" >
Category(s): JavaScript, Programming, Tips and Tricks
Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *