HTML Button Code

This page contains HTML button code — code for creating a button on an HTML document.

To create an HTML button, you need to use the HTML <button> tag. The button can be nested inside a <form> element or it can stand alone.

Basic Button Example

Here's an example of an HTML button:

Source CodeResult

The above button consists of a start and an end tag. Enclosed between these tags is the contents of the button. In this case it's the text "My Button".

Yes you can click on the button but it doesn't do much. In the next example, we'll make our button actually do something when you click on it.

Source CodeResult

The above example uses JavaScript to display an alert box to the user whenever they click the button.

Submit & Reset Buttons

A button can be used to submit the contents of a form. To do this, use type="submit".

To make the button a "reset" button (i.e. it resets the contents of the form that it is associated with), use type="reset".

Here is an example of a form with both a "submit" and a "reset" button.

Source CodeResult
Pick a color: Red Green Blue

A Note on Usability

Think carefully before implementing a "reset" button. Users can accidentally click this button when they meant to click the "submit" button. This can be incredibly frustrating, especially on a long form where the user has just spent a considerable amount of time entering the details — only for it to be wiped away with a single click!

If you do decide to implement a "reset" button, be sure to position it in a place where it is less likely to be confused with the "submit" button. Also consider styling it in such a way to reduce the likelihood of accidental clicks. Also consider styling the "submit" button in a way that makes it stand out as the obvious button to click.

Menu Button

The <button> tag also accepts a type attribute value of menu.

If the type attribute has a value of menu, the menu attribute must be provided in order to specify the element's menu. The value must be the ID of a <menu> element in the same home subtree whose type attribute is in the popup menu state. The menu attribute can only be used when the type attribute has a value of menu.

Source CodeResult

The above example is very simplistic, in order to demonstrate the concept. In reality, you would attach a script to each menu item so that clicking on that item would trigger a result.

Note that browser support for the <menu> element is extremely limited at the time of writing, hence the example might not appear correctly for you.

Disabling a Button

You can disable a button by using the disabled attribute. You could use this in conjunction with a script to enable/disable the button depending on whether certain criteria has been met.

Source CodeResult