An Interest In:
Web News this Week
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
Quick Tip: always include a type on your buttons
Did you know the default type
value on a button
element isnt button?
To step back for a moment, the button
element was introduced as part of HTML 4 specification in the late 90sits 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 buttons behavior.
type
takes three possible values, all of which are fairly self-evident. To quote the HTML Standard spec:
submit
- submits the formreset
- resets the formbutton
- 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
isnt 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, lets say youre building a form and it calls for a dialog with more information. You may put a button trigger for that dialog. If you dont include a type
on that button, clicking that button will submit the form before the users ready! Heres 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.
Original Link: https://dev.to/heyitsstacey/quick-tip-always-include-a-type-on-your-buttons-3cbh
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To