Prevent All Buttons From Submitting Forms

I recently got bit by this gotcha! The default type attribute of <button> is ‘submit’. This means that all <button> elements in a form will trigger submission unless they are explicitly assigned a type attribute of ‘button’ or ‘reset’.

In the following example both the submit and cancel buttons will actually submit the form.

<form>
  <input type="text" name="data" />
  <button>submit</button>
  <button>cancel</button>
</form>

Adding the type value of ‘button’ prevents this behaviour.

<form>
  <input type="text" name="data" />
  <button>submit</button>
  <button type="button">cancel</button>
</form>
Tags: HTML