TIP: Set “type” attributes explicitly on <button> elements

File under “Tiny little HTML5 useful tip.”

TL;DR

Apply this habit to all buttons contained within a form. Buttons outside of forms are just
buttons, not form controls.

(Note: originally written on January 22, 2016.)

Found out yesterday (January 21, 2016) that using a element to toggle form views can trigger constrain validation tooltips on forms with at least one input that has the required attribute but has no value entered or option selected. This is noticeable in Firefox, which displays a tooltip that reads something like, “Please select/enter a value.”

Here’s the button markup, with an Angular directive:

<button data-ng-click="cancelEdit()">Cancel</button>

In this case of view toggling, we don’t want to submit the form, but want to cancel out of it and show another view. With the markup above, we could change the view, but would see the validation tooltip (which of course makes no sense). To suppress the tooltip in that case, the button element should have its type attribute set explicitly to "button" ~ i.e,

<button type="button" ...>

Hours were spent chasing down the cause. Finally I went to the WHATWG button element spec itself, according to which, for the type attribute, “The missing value default is the Submit Button state.” Further down, this has implications on the behavior:

Constraint validation: If the type attribute is in the Reset Button state, the Button state, or the Menu state, the element is barred from constraint validation.

Ah! So, apparently, Firefox follows that spec, while certain others appear not to. To them,
a button is just a button (which appears to me more logical, if incorrect).

UPDATED same day (2016 Jan 22)

This rule goes for all buttons contained within a form. I found that a “link” was actually
a button styled as a link. The link was used for “deleting” – and, of course, the
delete request would be sent, followed by a post from the “save” button. Adding type="button" cured this double submission.

Apply this habit to all buttons contained within a form. Buttons outside of forms are just
buttons, not form controls.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s