Disable form submit on enter keypress March 13, 2005

Posted by Slobodan Kovacevic in : Programming , comments closed

I needed a JavaScript function that disables form submission when enter key is pressed. I’ve looked around and all solutions worked only in IE and I needed it to work in FireFox as well.

Finally after some more reading I found a solution how it can be done. Here is the function that I created:

<script language="JavaScript">
function disableEnterKey(e)
{
     var key;

     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox

     if(key == 13)
          return false;
     else
          return true;
}
</script>

All you need to do is to add onKeyPress event to, for example, text element and call this function. Something like this:

<input type=”text” name=”mytext” onKeyPress=”return disableEnterKey(event)”>