How do I submit a form when the return key is pressed?
To submit a form upon pressing the return (or Enter) key, include an <input type="submit">
within the form. Many browsers automatically trigger form submission on Enter if there's a submit button in place. Here's a basic example:
With the type="submit"
input kept hidden, the form gets submitted without visibly displaying a button.
JavaScript for additional control
Need more control or intention on handling extra functionalities such as form validation? You can extend the natural browser behaviour using JavaScript.
And with .hidden-button
, make sure it remains invisible in its power suit:
Cross-browser compatibility and accessibility
From ensuring cross-browser compatibility to maintaining user accessibility, web development these days require the code to be more adaptable and versatile. This means you can't really use style="display: none"
. It might sideline certain older browsers and potentially cause issues with screen readers.
Rather, using visibility: hidden
or placing items offscreen (like above) can be more effective. Keyboard users also won't be trapped inside invisible elements with tabindex
set to -1
.
Catering for style preservation
At times, you'd want to go invisible on your button but still keep its relevance in the document. Styling the <button>
as a div-like block element can solve the problem while retaining its functionality.
Checklist for efficient submission
- Form validation: Avoid incomplete or flawed submissions.
- Handle form submission based on keyCode inside JavaScript functions.
- Use pure HTML forms for users with JavaScript disabled.
- Regularly follow HTML5 specifications and guidelines.
Managing edge cases
- Autocomplete: Forms may be submitted upon autocomplete option selection in certain browsers. Plan accordingly!
- Browser defaults: Understand and plan for different browser behaviours on the Enter key press within forms.
- Progressive enhancement: Your core form functionality should work independent of JavaScript. Improve on that.
Practical scenarios
- Making JavaScript-driven form submission work for older browsers.
- Designing mobile-friendly forms where 'Go' button works like Enter.
- Using AJAX to submit forms without refreshing the page.
Was this article helpful?