Home > Web Front-end > JS Tutorial > How to Prevent a Button from Submitting a Form in HTML and JavaScript?

How to Prevent a Button from Submitting a Form in HTML and JavaScript?

Barbara Streisand
Release: 2024-10-29 04:22:29
Original
467 people have browsed it

How to Prevent a Button from Submitting a Form in HTML and JavaScript?

How to Prevent a Button from Submitting a Form

In HTML, when a button is clicked within a form, it typically triggers the form submission. However, there are scenarios where you may want a button to perform a specific action without submitting the form.

Consider the following form:

<code class="html"><form id="myform">
  <label>Label
    <input />
  </label>
</form>
<button>My Button</button></code>
Copy after login

In this example, clicking the button still triggers the form submission even though it's outside the form element. To prevent this unwanted behavior, you can specify the type="button" attribute for the button:

<code class="html"><button type="button">My Button</button></code>
Copy after login

Alternative Solution via JavaScript

If you prefer to handle this using JavaScript, you can disable the default form submission behavior. Here's an example using event listeners:

<code class="html"><button onclick="event.preventDefault();">My Button</button></code>
Copy after login

In this case, the event.preventDefault() function prevents the form from submitting when the button is clicked.

Conclusion

By specifying type="button" for the button or using JavaScript to suppress the default action, you can prevent a button from submitting a form even when it's located outside the form element.

The above is the detailed content of How to Prevent a Button from Submitting a Form in HTML and JavaScript?. 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