HTML: button

The <button> element creates a control that performs an action when the user activates it.

What you will learn

Choose navigation, form submission, or an on-page action

Navigate to another page

<a href="a.html">Read how to make a link</a>

Use a link when there is a destination URL. This preserves browser features such as opening a new tab and copying the link.

Submit a form

<form action="/save" method="post">
  <label for="display-name">Display name</label>
  <input id="display-name" name="displayName" required>
  <button type="submit" name="action" value="save">Save</button>
  <button type="submit" name="action" value="preview"
          formaction="/preview">Preview</button>
</form>
Three different uses of action
MarkupPurpose
form action="/save"The form’s default destination
button formaction="/preview"A destination override for that submit button
name="action" value="save"A field name and value sent with the form, not a destination URL

Change content on the same page

<button id="details-button" type="button"
        aria-expanded="false" aria-controls="details">Show explanation</button>
<p id="details" hidden>Here is some more information.</p>
const button = document.querySelector("#details-button");
const details = document.querySelector("#details");
button.addEventListener("click", () => {
  const open = button.getAttribute("aria-expanded") !== "true";
  button.setAttribute("aria-expanded", String(open));
  details.hidden = !open;
  button.textContent = open ? "Hide explanation" : "Show explanation";
});

This example also needs JavaScript to toggle the content. type="button" prevents it from becoming a submit button when placed inside a form.

Try toggling content and checking form data

Check the destination and form data

This demo shows the destination and form data. It does not send or save anything.

/save and /preview stand for handlers you would create on a server. Writing this HTML does not create a storage handler.

Use requestSubmit(button) in JavaScript to follow the normal submission process. form.submit() skips constraint validation and the submit event. With multiple submit buttons, specify which button should submit.

Button types

<button type="button">Open details</button>
<button type="submit">Send form</button>
<button type="reset">Clear form</button>

Inside a form, explicitly set type="button" for a button that should not submit. Otherwise the default type can behave like a submit button.

Submit a form

<form action="/search" method="get">
  <label for="query">Search</label>
  <input id="query" name="q">
  <button type="submit">Search</button>
</form>

Button or link?

Use a button for an action on the current page, such as opening a dialog or changing a setting. Use <a href> when the user should navigate to another URL.

Common mistakes