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

Tags: ,

Saturday, June 18th, 2011 JavaScript, Programming, Tips and Tricks

Leave a Reply


Comments are moderated due to spammers. Your comments will not appear until I review and approve them. If you left a question I will answer as best I can so be sure to check back.