Explain Codes LogoExplain Codes Logo

Submitting a form by pressing enter without a submit button

html
responsive-design
accessibility
best-practices
Nikita BarsukovbyNikita Barsukov·Nov 19, 2024
TLDR

To submit a form by pressing Enter without a visible submit button, use the <input> element inside <form>. Pressing Enter while focused on input will submit it because of inherent browser behaviour.

<form action="submit"> <input type="text" name="field"> <!-- Is it a bird? Is it a plane? No, it's a Form Submit Ninja! --> </form>

Just put the focus on the input field, press Enter, and voila! The form is submitted without a visible button.

The invisibility cloak: Using hidden attribute

What if you want to be the Houdini of form submission? You can have your invisible submit button using hidden attribute.

<form action="submit"> <input type="text" name="field"> <input type="submit" hidden> <!-- Now you see me, now you don't! --> </form>

The form has a submit button, but like Harry Potter's invisibility cloak, it's not visible to the muggles.

Prioritizing accessibility

Do remember, while the button stays invisible to the eyes, it doesn't fool the screen readers. Design for everyone. Like a programming Samurai, for whom respect for all, is an important creed.

How about old browsers?

But wait, what if your users are having a trip down memory lane using older browsers like IE7? Use position: absolute for smooth compatibility.

<input type="submit" style="position: absolute; left: -9999px; width: 1px; height: 1px;" tabindex="-1" /> <!-- The CSS ninja strikes again! -->

The tabindex="-1" will help to escape keyboard's tab navigation.

Design for all conditions

Even if CSS goes on vacation, your form stays classy. For moments like these, your off-screen method becomes your saviour.

Be the master of all situations

While the mystic arts of JavaScript and jQuery can add a touch of magic to detect Enter keypress, the true master is the one who can also work without it.

$('form').on('keypress', function(e) { if (e.keyCode === 13) { $(this).submit(); /* A wild Enter key appears. Boom! It's super effective! */ } });

But remember, distribute wisdom universally. You never know when users have JavaScript off.

Always test your potion

Different devices and browsers have different tastes. Only agility and comprehensive testing would ensure your hidden submission trigger is a universal darling.

To suit all taste buds

Beyond old browsers, the challenge lurks on phones, tablets, and myriad devices. They all come with unique behaviors ready to spice up your test scenarios.