philipp philipp - 1 year ago 83
Javascript Question

Observe Form Submission

In my application I need to submit forms via JavaScript. I know that I can do that with this code:

[...document.querySelectorAll('form')].forEach(form => {
form.addEventListener('submit', e => {
//doing the processing here

From the server I get completely generated forms as HTML, which I inject into the DOM (or delete them from there), whenever necessary. By doing so, the registered event handlers stop to work, because the form element is either deleted or not registered.

Is it possible to register a global »Submission Listener«, comparable to that:

window.addEventListener('click' e => { … });

what will never be removed if the DOM changes, or will I have to register the submission handlers each time the DOM changes?

Is not a dublicate, because the mentioned delegation strategy is what I am looking for, but not for click events, for submission events instead.

Answer Source

You can definitely catch submit events as they bubble up, so what you want can be achieved by listening from a parent element that is always present as the dynamic forms are added and removed. I like doing this thing with a wrapper element with an ID, as opposed to listening a the body or html level. Here's a very simple example using just vanilla js. Codepen here:


<div id="form-wrapper">
  <h2>Form 1</h2>
  <form id="form1">
    <input name="test" placeholder="enter something" />
    <input type="submit" value="submit" />

  <h2>Form 2</h2>
  <form id="form2">
    <input name="test" placeholder="enter something" />
    <input type="submit" value="submit" />
<button id="form-adder">
  + Add a form


var formWrapper = document.getElementById('form-wrapper');

// capture the submit event in the parent div
formWrapper.addEventListener("submit", function(e) {
  console.log('submit captured');

  var thisForm = e.srcElement || e.originalTarget;
  console.log('form id:' +;

// dynamically add divs and see we can still capture the submit
var divNum = 3;
function addDiv(e) {

  formWrapper.innerHTML += '<h2>Form ' + divNum + '</h2>\
  <form id="form' + divNum + '">\
    <input name="test" placeholder="enter something" />\
    <input type="submit" value="submit" />\


document.getElementById('form-adder').addEventListener('click', addDiv);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download