Home  >  Article  >  Web Front-end  >  How to Stop an External Button from Submitting a Form in HTML?

How to Stop an External Button from Submitting a Form in HTML?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 16:22:02183browse

How to Stop an External Button from Submitting a Form in HTML?

How to Prevent an HTML Button from Submitting a Form

In web development, placing a button outside a form typically allows you to execute JavaScript or other custom actions upon clicking. However, in certain cases, these external buttons may unintentionally submit the form they're placed near. This can be frustrating when you want the button to perform a separate function.

Consider the following scenario:

<code class="html"><form id="myform">
    <label>Label <input /></label>
</form>
<button>My Button</button></code>

When you click the "My Button" element, you might expect it to trigger JavaScript. However, it unexpectedly submits the myform.

To resolve this issue, the button's HTML code must be modified to prevent it from submitting the form:

<code class="html"><button type="button">My Button</button></code>

Adding the type attribute with a value of "button" explicitly specifies that the button is not intended to submit the form, thereby disabling its submit functionality.

Update (February 5, 2019):

According to the HTML Living Standard and the HTML 5 specification, the absence of a type attribute or an invalid value for the type attribute causes the button to default to the Submit Button state.

The above is the detailed content of How to Stop an External Button from Submitting a Form in HTML?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn