Home > Web Front-end > JS Tutorial > How Can I Prevent a Button from Submitting an HTML Form?

How Can I Prevent a Button from Submitting an HTML Form?

Patricia Arquette
Release: 2024-12-21 03:38:09
Original
323 people have browsed it

How Can I Prevent a Button from Submitting an HTML Form?

Preventing Form Submission on Remove Button Click

In the provided HTML form, the "remove" button triggers form submission when clicked. To prevent this behavior, it's essential to understand that the HTML5 button element has a default behavior of submitting the form, as defined by the W3C specification.

To override this default behavior, explicitly specify the button's type as a button:

<button type="button">Remove Last Item</button>
Copy after login

By setting the type attribute to "button," you instruct the browser to treat the button element as a button that initiates custom JavaScript code (in this case, the removeItem() function) instead of submitting the form.

<script>
  function removeItem() {
    // Custom code to remove the last row
  }
</script>
Copy after login

This modification ensures that the "remove" button will no longer submit the form when clicked, allowing you to perform other actions, such as removing a row from a table or updating data in an application, without triggering form submission.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template