Can I make a `` not submit a form?
Don't make your <button>
a secret agent! Instead of secretly submitting forms, type="button"
turns it into a well-mannered button:
Using type="button"
ensures actions can be performed without any "Mission Impossible"-style form submissions.
HTML-only approach: Using <input>
When JavaScript is out of reach or you prefer remaining in HTML territory, use the <input>
element with type="button"
:
This approach allows you to maintain the non-submitting behavior of a button directly within your HTML code.
Navigation-friendly approach: Pairing <a>
and <button>
When you need to navigate without triggering a form submission, combine the powers of <a>
and <button>
:
This combo works optimally for elements that resemble <button>
in appearance but function similar to <a>
tags.
Action-packed approach: onclick
attribute
To bind a specific action to your button, meet my friend onclick
:
With this approach, your custom JavaScript function braves the click event, separating form submissions from button actions.
Additional approaches: jQuery UI and Custom Styles
Button functionality and style often hold hands in web development. While using libraries like jQuery UI, ensure button style doesn't crash into default submission behavior:
When working with libraries or custom styles, double-check the type
settings to avoid accidental form submissions.
Making the form behave
Don't want ANY submission from your form? A 'thou shall not pass' approach using onsubmit
attribute should work:
Though effective, this Gandalf move impacts all elements within the <form>
. It's usually better to manually set the individual button types to "button"
.
Was this article helpful?