Home >Web Front-end >JS Tutorial >How to Stop HTML Buttons from Submitting Forms?
How to Prevent Form Submission from Buttons
Problem:
In certain scenarios, such as using HTML5 button elements for adding or removing items, it's essential to prevent the remove button from triggering form submission. While the add button does not submit the form, the remove button does. This issue requires a solution to disable form submission for the desired button.
Solution:
The default behavior of HTML5 button elements is to submit the form they are contained in. To override this behavior, an explicit type attribute must be specified. By setting the type to "button" instead of the default "submit," we can prevent the button from triggering form submission.
The corrected code snippet below demonstrates how to achieve this modification:
<button type="button" onclick="removeItem(); return false;">Remove Last Item</button>
Explanation:
The "type" attribute in HTML elements defines the type of button being used. Setting it to "button" clearly indicates that the button's purpose is to execute a JavaScript function without additional form actions. The "return false;" statement further prevents form submission when the button is clicked.
By making this change, the remove button will no longer cause form submission, while the add button continues to function as intended without submitting the form.
The above is the detailed content of How to Stop HTML Buttons from Submitting Forms?. For more information, please follow other related articles on the PHP Chinese website!