Home  >  Article  >  Web Front-end  >  How to Listen to Form Submit Events in JavaScript Without Modifying HTML?

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-28 03:37:01121browse

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>

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>

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>

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!

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