Home > Web Front-end > JS Tutorial > body text

How to Listen to Form Submit Events in JavaScript Without Modifying HTML?

Linda Hamilton
Release: 2024-10-28 03:37:01
Original
120 people have browsed it

How to Listen to Form Submit Events in JavaScript Without Modifying HTML?

Listening to Form Submit Events in JavaScript without Modifying HTML

In this article, we address the common challenge of listening to form submit events without having to modify the HTML code. Instead of relying on onClick or onSubmit attributes in HTML, we provide a pure JavaScript solution.

To achieve this, we leverage the EventTarget.addEventListener method. This method allows us to register a callback function that will be executed when a specific event occurs on a form element.

<code class="javascript">var ele = /*Your Form Element*/;
if (ele.addEventListener) {
  ele.addEventListener("submit", callback, false); // Modern browsers
} else if (ele.attachEvent) {
  ele.attachEvent('onsubmit', callback); // Old IE
}</code>
Copy after login

Replace "ele" with the reference to your form element and "callback" with the function you want to execute when the form is submitted.

To prevent the native form submission behavior (i.e., refreshing the page), use the .preventDefault() method within your callback function:

<code class="javascript">document.querySelector("#myForm").addEventListener("submit", function (e) {
  if (!isValid) {
    e.preventDefault(); // Stop form from submitting
  }
});</code>
Copy after login

Listening to Submit Events with Libraries

While not necessary, you may prefer using a library to listen to submit events. Here's how you can do it using common libraries:

jQuery

<code class="javascript">$(ele).submit(callback);</code>
Copy after login

Example

[jsfiddle.net/DerekL/wnbo1hq0/show](http://jsfiddle.net/DerekL/wnbo1hq0/show)

By using these techniques, you can easily listen to form submit events in JavaScript without having to touch the HTML code.

The above is the detailed content of How to Listen to Form Submit Events in JavaScript Without Modifying HTML?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!