HTML BasicsLesson 15 of 36

HTML Buttons

The button tag creates a clickable control on your page. It can hold plain text, and it can hold other elements like icons and images. Shopping carts, forms, play buttons, they all start with this one tag. A button is the simplest way to let a visitor do something.

The button tag creates a clickable control on your page. It can hold plain text, and it can hold other elements like icons and images. Shopping carts, forms, play buttons, they all start with this one tag. A button is the simplest way to let a visitor do something.

On its own, a button does nothing. You give it a job in one of two ways. Inside a form, a button can submit the form data to a server. Outside a form, an onclick attribute connects it to JavaScript, and that code runs the moment someone clicks.

The type attribute decides the role. type="button" makes a plain click target. type="submit" sends the surrounding form. type="reset" clears the fields. Here is the gotcha: inside a form, a button with no type acts as submit. Forgetting that sends the form when you wanted a plain button.

Connecting a click

To make a button do something, add an onclick attribute with JavaScript inside the quotes. The browser runs that code when the button is clicked. Keep the code short, or call a function you defined in a script tag, which keeps the button readable and the logic reusable.

HTML
<button onclick="alert('Hello!')">Click me</button>

The submit surprise

Inside a form, any button without an explicit type acts as a submit button. A harmless-looking button can reload the page or send data when all you wanted was a toggle. Always set type="button" on buttons that should not submit, and reserve the default behavior for the real submit button.

HTML
<form action="/save">
  <input type="text" name="message">
  <button type="submit">Send</button>
</form>

Syntax

HTML
<button onclick="alert('Hi there!')">Say hello</button>

<button> In a Form Defaults to Submit - Your 'Cancel' Button Submits

If you write <button>Close</button> inside a <form> with no type, HTML5 spec says it equals type="submit" and submits the form, reloading the page. This is the #1 'form submits when I click button' bug on Stack Overflow (183↑). Fix: always write type="button" for non-submit actions, type="reset" for resets.

HTML
<form><button type="button" onclick="close()">Cancel</button><button type="submit">Send</button></form>

Good to know

  • The button tag creates a clickable control.
  • Use type="button" for plain buttons; submit sends the form.
  • Inside a form, a button without a type acts as submit.
  • onclick runs JavaScript when the button is clicked.
Try it Yourself Edit the code, press Run, then check what changed in the Result.
Ready
Code
Result

Practice makes it stick

Open the Playground and build your own page with the tags you just learned.

→ Open Playground