Do not wipe form HTML during submit event

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the javascript category.

Last Updated: 2021-05-15

I had the following code intended to perform some work before submitting a form (via HTML submission controlled by JavaScript - not pure AJAX)

emailSubscribeForm.addEventListener('submit', addedEmail)

// This function, since it doesn't mess with event.preventDefault() should not
// stop events... but it _did_ stop the submission for some reason...
function addedEmail(event) {
  let email_subscribe_modal_content = document.querySelector("#email-subscribe-modal .modal-content");

  // Give feedback to the end user.
  new_content = "<h1>subscribed!</h1><p>thank you</p>";
  email_subscribe_modal_content.innerHTML = new_content;
}

When I checked the JavaScript console, I saw "Form submission canceled because the form is not connected".

Essentially what was happening, I learned, was that I was destroying the form (clobbering it with feedback) before it had the chance to be submitted.

Here's the working version... Notice how the part that gives feedback to the user (by removing the form content) is now delayed until after the submit event that sends the form data terminates normally. This gives the browser time to submit the form.

function addedEmail(event) {
  let email_subscribe_modal_content = document.querySelector("#email-subscribe-modal .modal-content");
  setTimeout(() => {
    if (email_subscribe_modal_content) {
      new_content = "<h1>subscribed!</h1><p>thank you</p>";
      email_subscribe_modal_content.innerHTML = new_content;

      let email_subscribe_footer_content = $("#email_subscribe_footer_content");
      email_subscribe_footer_content[0].innerHTML = new_content;
    }
  }, 3000)
}