Detecting Form Submissions Without Modifying HTML
To detect form submissions in JavaScript without resorting to HTML event attributes like onSubmit or onClick, you can utilize the addEventListener or attachEvent methods of the form element.
Using EventTarget.addEventListener
For modern browsers that support the addEventListener method, the syntax is as follows:
<code class="javascript">var ele = /*Your Form Element*/; if(ele.addEventListener){ ele.addEventListener("submit", callback, false); }</code>
Using EventTarget.attachEvent
For older versions of Internet Explorer that don't support addEventListener, use attachEvent instead:
<code class="javascript">else if(ele.attachEvent){ ele.attachEvent('onsubmit', callback); }</code>
In both cases, callback is the function you want to execute when the form is submitted.
Preventing Default Submission
If you need to prevent the form from submitting natively, use e.preventDefault() within your callback function:
<code class="javascript">document.querySelector("#myForm").addEventListener("submit", function(e){ if(!isValid){ e.preventDefault(); } });</code>
Library Integration
If using a library is preferred, here are some popular options for listening to the submit event:
jQuery:
<code class="javascript">$(ele).submit(callback);</code>
The above is the detailed content of How Can I Detect Form Submissions in JavaScript Without Modifying HTML?. For more information, please follow other related articles on the PHP Chinese website!