Button Types
Overview
The `<button>` tag seems simple, but it actually has three different 'personalities' depending on its `type` attribute.
If you don't explicitly declare what `type` of button it is, it can cause massive bugs—especially when placed inside a `<form>`, where it might accidentally refresh the page or submit data when you didn't want it to!
Syntax
If a button is inside a `<form>`, its default type is AUTOMATICALLY `submit`. When clicked, it packages up all the input data and sends it to the server, reloading the page.
<form action="/login">
<input type="text" name="user" />
<!-- These two buttons do the EXACT SAME THING -->
<button type="submit">Log In</button>
<button>Log In</button>
</form>If you just want a button that triggers some custom JavaScript (like opening a popup menu or closing a modal), you MUST add `type="button"`. This tells the button: 'Do not submit the form, just sit there and let JavaScript handle it'.
<form>
<input type="text" />
<!-- Clicking this will NOT refresh the page -->
<button type="button" onclick="showHelpPopup()">Help?</button>
<!-- Clicking this WILL submit the form -->
<button type="submit">Submit</button>
</form>`type="reset"` will instantly clear all the inputs in the form, putting them back to their default empty states. This is rarely used today because users hate accidentally deleting all their hard work.
<form>
<!-- Erases all typed data! -->
<button type="reset">Clear Form</button>
</form>Common Pitfalls
- Always, always, always add type='button' to any button that isn't meant to submit a form. If you forget, and you click 'Cancel' on a form, it might actually submit the form data instead of canceling!
Real-World Example
A search bar with a submit button and a JavaScript-powered voice search button:
<form action="/search" method="GET">
<input type="text" name="q" placeholder="Search Google..." />
<!-- Submits the search -->
<button type="submit">Google Search</button>
<!-- Just triggers a JS function, does NOT submit the form -->
<button type="button" onclick="startMicrophone()">
🎤 Voice Search
</button>
</form>