Explain Codes LogoExplain Codes Logo

Prevent form submission on Enter key press

javascript
event-delegation
error-handling
modern-javascript
Nikita BarsukovbyNikita Barsukov·Sep 6, 2024
TLDR

To prevent form submission upon pressing Enter, attach a handler to the form's keypress event. In the handler, check if event.keyCode === 13 (Enter key's code) and call event.preventDefault() to stop the submission.

document.querySelector('form').addEventListener('keypress', function(event) { if (event.keyCode === 13) { // Whoa there! The Form Police stops submissions on '13' event.preventDefault(); } });

Embracing the modern: event.key

The days of keyCode are past. Modern browsers include an event.key property for more readable code. It's like taking your JavaScript from black & white to 4k resolution.

document.querySelector('form').addEventListener('keypress', function(event) { if (event.key === 'Enter') { // 'Enter key' tried to sneak past, but we're always on guard! event.preventDefault(); } });

Legacy browser compatibility: Polyfill

The internet doesn't forget its legacy browsers. A polyfill can provide event.key support where it's lacking because, in code, no browser is left behind.

if (!('key' in KeyboardEvent.prototype)) { var keyMap = { 13: 'Enter' }; Object.defineProperty(KeyboardEvent.prototype, 'key', { get: function() { // Old but Gold! Using keyCode for good old browsers. return keyMap[this.which || this.keyCode]; } }); }

Robust Error Handling: Safety first!

Error checks are the seat belts of your application. They ensure it won’t crash due to unforeseen bumps and hitches. Remember, safety code is the best code!

Dynamic forms: Event delegation

Event delegation allows us to predictably handle events for dynamic inputs. Attach the listener to a parent that's always present, and use event.target in the handler.

document.addEventListener('keypress', function(event) { if (event.target.tagName === 'INPUT' && event.key === 'Enter') { // Dynamic inputs can't surprise us anymore! event.preventDefault(); } });

Modern JavaScript

Modern syntax with arrow functions and destructuring elevates your code to impressive levels of conciseness and readability.

document.addEventListener('keypress', (event) => { let { key, target } = event; if (target.tagName === 'INPUT' && key === 'Enter') { // If a keypress occurs in an input, stop it (in style)! event.preventDefault(); } });

Better UX: Broadcast the halt!

Uplift the user experience by providing an alert or message when a form prevents submission on Enter. Augusto Boal said, "Theater is a form of knowledge; it should and can also be a means of transforming society." We say, "So can interactive web forms!"