Home >Web Front-end >JS Tutorial >How to Stop Form Buttons from Refreshing the Page?

How to Stop Form Buttons from Refreshing the Page?

DDD
DDDOriginal
2024-12-06 06:23:15678browse

How to Stop Form Buttons from Refreshing the Page?

Preventing Page Refresh with Form Buttons

When creating forms with buttons, it's common to encounter an issue where button clicks trigger unwanted page refreshes. This can be problematic, especially if the page contains dynamically loaded data that gets reset upon refresh.

Issue Description

In the provided code snippet:

<form method="POST">
    <button name="data" onclick="getData()">Click</button>
</form>

Clicking the button calls the getData() function, but it also automatically refreshes the page. This occurs because the default type for a button in a form is "submit," which initiates a form submission and reloads the page.

Solution

To prevent page refresh, modify the button's type attribute to "button" like this:

<button name="data" type="button" onclick="getData()">Click</button>

By setting type="button", the button no longer initiates a form submission. Instead, it behaves like a regular button that solely triggers the specified onclick event without affecting the page.

Explanation

The type attribute defines the type of button. The possible values are:

  • submit: Submits the form. This is the default value.
  • reset: Resets the form to its initial state.
  • button: Acts as a custom button without submitting or resetting the form.

By setting type="button", you effectively convert the button into a non-submitting button that simply triggers the desired JavaScript function without causing page refreshes.

The above is the detailed content of How to Stop Form Buttons from Refreshing the Page?. 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