Submit form with Enter key without submit button?
To submit a form using the Enter key without showing a submit button, embed a hidden submit input. Let's look at the code:
By hitting Enter in the text field, the form gets submitted courtesy of the invisible submit input. Want a surprise? No JavaScript was harmed in doing this!
Going deeper: leveraging jQuery for enhanced control
The quick solution provided does the job. But when it comes to the real-world scenarios, where you require more granular control—Enter stage jQuery!
Manipulating default behavior using jQuery
With jQuery, you can control your form's destiny—or rather, its submission behavior:
This code snippet listens for Enter keypress (i.e., keyCode 13) and halts the default form action, just to allow submission on this specific cowbell...I mean Enter key.
Invisible cloak: the CSS magic
In some scenarios, you might need to wield the power of invisibility on the submit button—display: none;
comes to your rescue!
The CSS trickery ensures the submit input doesn't visually materialize but guarantees the form's submission with the magic wand...I mean the Enter key.
Keydown event: a faster route
Using keydown
over keypress
allows us to trigger the submission as soon as the keydown event is detected, cutting down on the delay caused by our keypress friend.
Solving the JavaScript dependency puzzle
What if the users have taken a vow against JavaScript? Fear not! We have a hidden warrior—a hidden submit element waiting to stand in for JavaScript!
This backup strategy operation triggers the hidden .js-submit
class when JavaScript is off-duty, thanks to our dear friend, noscript
tag.
Handling multiple actors in the play: inputs and forms
When your casting call includes multiple input fields or forms, a tailored approach is needed. Thanks to jQuery, we've got it covered!
Targeting specific forms: use the ID card!
By assigning and using an ID for your form, you can ensure the right form gets submitted when there's a horde of forms on screen.
Sneaking through closest form: jQuery got your back
Using jQuery's closest()
method provides a path to the nearest form in the DOM jungle around the current input and submits it.
Was this article helpful?