0

I'm trying to make a simple email subscription (newsletter) form on a website. After a person subscribes, the message "Thank you for subscribing" should appear.

I have two of these forms in total, one at the top of the page and the second one at the bottom. But only the top one works and I don't understand why the bottom form doesn't.

Here is HTML:

<form action="" class="newsletter-form" name="submit-to-google-sheet">
   
   <input type="email" name="email_address" placeholder="Your email address" required
   class="email-field">
   
   <button type="submit" class="btn">Subscribe</button>
 
</form>
                
<span id="msg"></span>

Here is JS:

const scriptURL = 'https://script.google.com/macros/s/AKfycbyGMBsff7lJwNtCuD1wteBqEOyxhKL0E9w9-niTUDu0pJeFPmsUitGNz73ZvMDAVhtk/exec'
const form = document.forms['submit-to-google-sheet']
const msg = document.getElementById("msg")

form.addEventListener('submit', e => {
    e.preventDefault()
    fetch(scriptURL, {
            method: 'POST',
            body: new FormData(form)
        })
        .then(response => {
            msg.innerHTML = "Thank you for subscribing!"
            setTimeout(function() {
                msg.innerHTML = ""
            }, 3000)
            form.reset()
        })
        .catch(error => console.error('Error!', error.message))
})
Usitha Indeewara
  • 870
  • 3
  • 10
  • 21
igblui
  • 1
  • 2
  • 3
    `document.forms['submit-to-google-sheet']` is a single element. Use [event delegation](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of adding several event listeners — it’s more maintainable and applies to dynamically added elements. See [the tag info](/tags/event-delegation/info) and [this Q&A](/q/1687296/4642212). Remove the `form` variable and use something like `addEventListener("submit", (event) => { const form = event.target.closest("[name='submit-to-google-sheet']"); if(form){` _the content of your listener here_ `} });`. – Sebastian Simon Oct 30 '22 at 13:16

0 Answers0