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:
Enter
when submit button is focused.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');
if ($attr === 'button' || $attr === 'submit') {
return true;
}
// Ignore keypress if all fields are not populated.
if (e.which === 13 && !fieldsArePopulated(this)) {
return false;
}
});
_x000D_