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))
})