In this post, I will discuss how to disable using the “enter key” to submit a a form. There are many subtle nuances in form behavior that many people don’t think about when using them. On most browsers, hitting the enter key while the focus is set to one of the form elements (text areas not included) the form will be submitted. If you have a submit button for the form (not required) the enter key actually simulates a click on the first submit button for the form.
In many cases, this behavior is beneficial and natural for form processing. Take for example the main google search page.
When you type text in the search field and then hit the enter key, the form is submitted and google does it’s search magic. There is no need to click the “google search” button to submit the form. People typically don’t think twice about this behavior… its quite natural. For most small forms (less than 4 form elements) this works quite well.
Think about entering a sales order form, form let’s say phpBMS.
There is a lot of information you need to enter before saving the record properly. When adding information, or new product line items, you might accidentally or instinctively hit the enter key. The default form submission would then immediately try to save the sales order record. This can be huge source of frustration for your users.
1. Set the form’s onsubmit
We are going to set the form’s on submit to return false – i.e. it wont submit the form.
<form id="theform" action="myaction.php" method="post" onsubmit="return false">
This is going to make sure that hitting enter will never submit the form. Unfortunately, it also prohibits submit buttons from submitting the form (which actually is a good thing.) So the next thing we need to do is enable the user to actually submit the form.
2. Create a submit function/button
<button onclick="submitForm()">Submit Form</button>
theform = document.getElementByID("theform");
This now gives us a single point for form submission. If we wanted to do form verification, we could do it right form inside this function. What’s more, the stoopid enter key no longer holds sway over us.