简体   繁体   中英

Adding eventListener to Submit-Button in a Form

I have a form with a submit button to send the form data to the next page. So far so good. But now there should be some javascript-code executed (for tracking reasons) when the user submits the form. So I tried to set an event-listener. Problem is: sometimes the code will execute and sometimes it will be ignored.

I set a timeout and figured out that all timeouts greater than 15ms won't execute the code and to browser is already on the form_test.html page.

 //secTimeout = 15; button = document.getElementById('submitbutton'); button.addEventListener("click", function() { // setTimeout(function(){ // console.log('log after ' + secTimeout + 'ms'); // }, secTimeout); // execute tracking tool });
 <form id="form1" action="form_test.html"> <input type="text" name="text1"> <input type="text" name="text2"> <input type="text" name="text3"> <input type="submit" id="submitbutton"> </form>

what would be a good proceeding to ensure to js-code will run every time?

The best way to add tracking functionnality is to handle the submission programmaticaly. So use a and get inspiration from this . By sending the form programmaticaly you can run any piece of code you want before sending.

A small example:

<form id="form1" action="form_test.html">
  <input type="text" name="text1">
  <input type="text" name="text2">
  <input type="text" name="text3">
  <button id="submitbutton">
</form>


button = document.getElementById('submitbutton');
button.addEventListener("click", function() {
  // execute tracking tool
  document.form1.submit();
});

The short answer is

  • you should receive an event parameter in your event-handling function
  • then you should prevent default on this event (because generally when you press the submit button, it submits the form)
  • then you should do your tracking code
  • then you should submit the form manually by calling submit method of the form

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM