Stacey
Posted on April 24, 2022
Did you know the default type
value on a button
element isn’t “button?”
To step back for a moment, the button
element was introduced as part of HTML 4 specification in the late 90s—it’s been with us awhile. Previously, if you wanted a submit button on a form, you would use an input
with a type="submit"
<input type="submit" value="Submit the form">
Increasingly, the button does more than just submit or reset form values. It opens dialogs! Navigates slideshows! All of our favorite things!
The modern button
element carries over many of the attributes of the original input
spec, including a type
that defines the button’s behavior.
type
takes three possible values, all of which are fairly self-evident. To quote the HTML Standard spec:
-
submit
- “submits the form” -
reset
- “resets the form” -
button
- “does nothing”
This is great for a number of reasons, especially because it makes it very clear to you or whoever has to read your code after you exactly what this button does.
The tricky part comes from when the type
isn’t set. If we have a button element without a type (<button>My Sample Button</button>
) or a button with an invalid type value <button type="resete">My Sample Button with mispelled "type"</button>
, the state defaults to submit
not button
.
(except in Internet Explorer, because IE always has to do its own thing)
This is an easy step to miss, and depending on your project, might not cause any obvious issues. Or it could cause very obvious issues.
For example, let’s say you’re building a form and it calls for a dialog with more information. You may put a button trigger for that dialog. If you don’t include a type
on that button, clicking that button will submit the form before the user’s ready! Here’s an extremely basic codepen example.
The lesson here, then, is always assign a value to your type
. It makes your code valid, readable, and saves your users headaches.
Posted on April 24, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.