Explain Codes LogoExplain Codes Logo

Jquery disable form submit on enter

javascript
event-handling
form-submission
ajax-submissions
Alex KataevbyAlex Kataev·Feb 27, 2025
TLDR

To block a form from submitting on Enter, bind a handler to the input that intercepts the keypress event. Check for Enter with event.keyCode === 13, and if true, prevent the submission with event.preventDefault(). Here's the boiled-down code:

$('input').keypress(function(event) { // If the door opens (Enter key), don't let in the tiger (the form submission) if (event.keyCode === 13) { event.preventDefault(); } });

However, let's take it a step further for more profound security and adaptability.

Home the strays: Robust event handling

The double guardian: Using keyup and keypress

Cover all your bases by using a combination of keyup and keypress events. This multi-layered approach ensures the form remains intact regardless of how browsers interpret your key events.

$('#myForm').on('keyup keypress', function(event) { // 13 is the door number. Watch out for door 13! var keyCode = event.which || event.keyCode; if (keyCode === 13) { event.preventDefault(); return false; } });

The efficient doorman: Using on()

The on() method efficiently binds multiple events, simplifying your syntax when applying several event handlers.

The postman approach: AJAX submissions

Deliver the message without disturbing the conversation by using AJAX submissions. This allows the form to validate and submit data without refreshing the page.

$('#myForm').on('submit', function(event) { event.preventDefault(); // The form offerings go to AJAX god here... var formData = $(this).serialize(); });

For the growing clan: Event delegation

When handling dynamically generated forms, event delegation ensures your scripts continue working even when new elements appear on your page post-load.

$(document).on('keypress', 'input', function(event) { // Again, beware of door 13! if (event.keyCode === 13) { event.preventDefault(); } });

User comfort: A friendly place

When disabling an expected form behavior, consider providing alternative user-friendly instructions or cues to avoid confusion.

Deep dive: More about form safety

Constant vigilance: Updating best practices

Always stay tuned for changes and make sure your codes practice the latest wisdom.

The shape-shifter: Handling different form ids and dynamic elements

No one-size-fits-all, so ensure to match your script to your form id or element.

Specialist handler: Custom events for special cases

For some cases, the regular event handlers aren't enough. Then, you might need a custom event.

Door for all: Accessibility considerations

Your form must be easy for all, including assistance users and keyboard navigators. Remember accessibility rules