jQuery: disable the Enter key on forms

We all know that sometimes submitting a form via the Enter key may be troublesome, especially when a user hits this key accidentally. A simple solution to this problem is to prevent users from submitting a form with this key. Let's see how.

We have the following test form:

<form action="javascript:document.write('Form submitted');" id="test" method="post">
    <div>
        <input type="text" name="text" id="text" />
        <input type="submit" name="submit" id="submit" value="Submit" />
    </div>
</form>​

Disabling the Enter key is only a matter of checking the correct value for the keyCode property of the event object:

$('#test').bind('keydown', function(e) {
    if (e.keyCode == 13) {
        e.preventDefault();
    }
});​

You can see the demo below.

Demo

Live demo

Back to top