Prevent users from submitting a form by hitting Enter
To instantly restrict the submission of a form on hitting Enter, we can employ jQuery. Here's a short yet effective solution that uses the keypress
event, checks for the Enter key code (13
), and calls the preventDefault()
function to cancel the form submission:
The above snippet attaches to the form, ensuring that any input field will not provoke a form submission when Enter is pressed.
Advanced form management
Beyond the quick fix, enhancements can help improve the user experience and the resilience of your forms. Let's roll up our sleeves and inundate our form handling with some advanced tricks:
Perfecting Validation
A robust validation mechanism is vital before a form submission. Embedding a validationFunction
inside our event handler ensures inputs are scrutinized properly:
Use jQuery's .each()
method to inspect form fields uniformly and offer improved accessibility by managing focus.
Spotting the right key
The keyCode
method, even though deprecated, was a good way to detect keys. The modern, reliable champ is the event.key
method:
Refining the submission method
An expert tip for handling form submissions effectively is to listen for form submission events directly:
Fallback for non-JS scenarios
Accessibility matters! When JavaScript is disabled in the client's browser, consider placing a hidden submit button at the beginning of the form:
Building the ideal form experience
Let's go beyond the basics, spot potential issues, and enrich the overall user experience:
Textareas are special
Textareas typically should allow the Enter key. To achieve this, we can make a sneak adjustment:
Medal for Consistency
Choosing $(document)
over $(window)
ensures a more uniform behaviour across different browsers:
Inline JavaScript: The last resort
I know we love tidiness. But desperate times call for desperate measures. As a last resort, place onsubmit="return false;"
directly in your <form>
tag:
Was this article helpful?