Prevent form submission with enter key

You can mimic the tab key press instead of enter on the inputs like this:

//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
    if ( e.which == 13 ) // Enter key = keycode 13
    {
        $(this).next().focus();  //Use whatever selector necessary to focus the 'next' input
        return false;
    }
});

You will obviously need to figure out what selector(s) are necessary to focus on the next input when Enter is pressed.


Note that single input forms always get submitted when the enter key is pressed. The only way to prevent this from happening is this:

<form action="/search.php" method="get">
<input type="text" name="keyword" />
<input type="text" style="display: none;" />
</form>

Here is a modified version of my function. It does the following:

  1. Prevents the enter key from working on any element of the form other than the textarea, button, submit.
  2. The enter key now acts like a tab.
  3. preventDefault(), stopPropagation() being invoked on the element is fine, but invoked on the form seems to stop the event from ever getting to the element.

So my workaround is to check the element type, if the type is not a textarea (enters permitted), or button/submit (enter = click) then we just tab to the next thing.

Invoking .next() on the element is not useful because the other elements might not be simple siblings, however since DOM pretty much garantees order when selecting so all is well.

function preventEnterSubmit(e) {
    if (e.which == 13) {
        var $targ = $(e.target);

        if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
            var focusNext = false;
            $(this).find(":input:visible:not([disabled],[readonly]), a").each(function(){
                if (this === e.target) {
                    focusNext = true;
                }
                else if (focusNext){
                    $(this).focus();
                    return false;
                }
            });

            return false;
        }
    }
}