Is there an attribute for form to prevent it submitting, or is preventDefault the only…
Private research annotation
Sign in to add a private research label or note.
- User
Is there an attribute for form to prevent it submitting, or is preventDefault the only way?
Assistant
There is no HTML attribute that can be added to a
formelement to prevent it from submitting. ThepreventDefault()method is one way to prevent a form from submitting, but it's a JavaScript method that needs to be called in an event handler.However, there are a few alternative approaches you can take:
- Use
event.preventDefault()in a JavaScript event handler: As you mentioned, you can add an event listener to the form'ssubmitevent and callpreventDefault()to prevent the form from submitting.
javascript- Use
- User
button type=button would be the cleanest way? Avoiding mixing markup and JS? Whilst also preventing the default action should JS fail to load or be disabled?
Assistant
Using a
buttonelement withtype="button"is indeed a clean and elegant way to prevent a form from submitting, while also avoiding mixing markup and JavaScript.By setting
type="button", you're telling the browser that this button is not a submit button, and it should not trigger the form's submission when clicked. This approach is also more accessible and semantic, as it provides a clear indication to screen readers and other assistive technologies that this button is not a submit button.Using
type="button"also provides a fallback behavior in case JavaScript is disabled or fails to load. Since the button is not a submit button, the form will not be submitted even if JavaScript is not available.In contrast, relying solely on JavaScript to prevent the form submission (e.g., using
event.preventDefault()) can be problematic if JavaScript is disabled or fails to load. In such cases, the form may still be submitted, which could lead to unexpected behavior.So, to summarize, using a element with is a clean, semantic, and accessible way to prevent a form from submitting, while also providing a fallback behavior in case JavaScript is not available.