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

How Can I Prevent a Button from Submitting a Form?

DDD
Release: 2024-12-02 05:28:11
Original
569 people have browsed it

How Can I Prevent a Button from Submitting a Form?

Customizing Button Behavior in Forms

In forms, it's common to have buttons that trigger different actions, such as submitting the form or performing other operations. However, in certain cases, it may be desirable for a button to not submit the form when clicked.

Problem:

Consider a form with two buttons: a "Cancel changes" button and a "Submit" button. Both buttons have the jQuery UI button style applied. However, the "Cancel changes" button also submits the form, even though it lacks the type="submit" attribute.

Solution:

The default value for the type attribute of button elements is "submit." To prevent a button from submitting the form, explicitly set type="button":

<button type="button">Cancel changes</button>
Copy after login

This modification instructs the browser that the button should "do nothing" when clicked, ensuring that the form remains unaffected.

Additional Notes:

  • The jQuery UI button() function can be used to enhance the appearance of both button and input[type="button"] elements.
  • It's important to note that setting type="button" will disable form validation for that button. If validation is desired, use type="submit" instead.

The above is the detailed content of How Can I Prevent a Button from Submitting a 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template