Block Enter Key Submit

Sometimes you want a form to submit when the enter key is pressed, most times you don’t… here’s the code to block it from happening…


function blockEnter(evt) {
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode :
          ((evt.which) ? evt.which : evt.keyCode);
    if (charCode == 13) {
        return false;
    } else {
        return true;
    }
}
<input onkeydown="return blockEnter(event);" name="search" size="40" type="text" />

3 comments

  1. In FF2 I’m getting:
    in your page: blokEnter is not defined
    I think the function isn’t included in your page.

    But using it in my page I get another error:
    setting a property that has only a getter

  2. My example on this page should only be showing the code… it wasn’t initially, but I fixed it now.

    Make sure you set up the javascript right… you need to wrap the js portion in script tags for the page to find it properly.

  3. There was a problem I was facing with a web form I made, and that was that whenever the user pressed the enter key while typing in a text box, he was taken to the previous page. Obviously it was very irritating so I thought about making up a javascript routine to eat away the Enter key. At first I made up a function using window.event and that was working perfectly fine until I discovered that it wasn’t working in Firefox 3. So I starting googling things out and came up with this function. This baby works fine in both browsers.

    And never forget this : PHP is server-side technology and therefore runs on the server – so there is no way for it to determine what keys where pressed at the client (aka the user).

    getElementById is not overrated its just not documented enough

Comments are closed.