Home >Web Front-end >JS Tutorial >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!