Prevent form submission with enter key

Viewed 100209

I just wrote this nifty little function which works on the form itself...

$("#form").keypress(function(e) {
    if (e.which == 13) {
        var tagName = e.target.tagName.toLowerCase(); 
        if (tagName !== "textarea") {
            return false;
        }
    }
});

In my logic I want to accept carriage returns during the input of a textarea. Also, it would be an added bonus to replace the enter key behavior of input fields with behavior to tab to the next input field (as if the tab key was pressed). Does anyone know of a way to use the event propagation model to correctly fire the enter key on the appropriate element, but prevent form submitting on its press?

10 Answers

From a usability point of view, changing the enter behaviour to mimic a tab is a very bad idea. Users are used to using the enter key to submit a form. That's how the internet works. You should not break this.

I modified Dmitriy Likhten's answer a bit, works good. Included how to reference the function to the event. note that you don't include () or it will execute. We're just passing a reference.

$(document).ready(function () {
    $("#item-form").keypress(preventEnterSubmit);
});

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;
        }
    }
}
Related