There are many good answers here already, I just want to contribute something from a UX perspective. Keyboard controls in forms are very important.
The question is how to disable from submission on keypress Enter. Not how to ignore Enter in an entire application. So consider attaching the handler to a form element, not the window.
Disabling Enter for form submission should still allow the following:
- Form submission via
Enterwhen submit button is focused. - Form submission when all fields are populated.
- Interaction with non-submit buttons via
Enter.
This is just boilerplate but it follows all three conditions.
$('form').on('keypress', function(e) { // Register keypress on buttons. $attr = $(e.target).attr('type'); $node = e.target.nodeName.toLowerCase(); if ($attr === 'button' || $attr === 'submit' || $node === 'textarea') { return true; } // Ignore keypress if all fields are not populated. if (e.which === 13 && !fieldsArePopulated(this)) { return false; } });