I am trying to make my webpage redirect to a thank you page after a user submits my registration form.
Below is the javascript event listener that I have been trying to use but not working. Any help will be appreciated.
window.addEventListener("load", function() {
const form = document.getElementById('submitForm');
form.addEventListener("submit", function(e) {
e.preventDefault();
const data = new FormData(form);
const action = e.target.action;
fetch(action, {
method: 'POST',
body: data,
})
.then(() => {
alert("https://www.google.com/");
})
});
});
<div class='testbox'>
<form action='https://script.google.com/macros/s/AKfycbyg4V7O2BTMG_u1QVROTCVhZlDo2viq3e2bcqjQ9X6ZBOCyBoQrkyJGK1Zw_gtFp6dw/exec' method='POST' enctype="multipart/form-data">
<div class='name-item'>
<input name='Surname' placeholder='Surname' required='' type='text'/>
<input name='First Name' placeholder='First Name' required='' type='text'/>
<input name='Middle Name' placeholder='Middle Name' required='' type='text'/>
</div>
<div class='question'>
<center><p>Privacy Policy<span class='required'>*</span></p></center>
<div class='question-answer checkbox-item'>
<div>
<center><label class='check' for='check_1'><span>By submitting this form you agree to the terms of service <a href='https://www.google.com/p/privacy-policy.html' target="_blank">privacy policy.</a></span></label></center>
</div>
</div>
</div>
<div class='btn-block'>
<center> <button href='/' type='submit' id="submitForm">Submit</button></center>
</div>
</form>
</div>
CodePudding user response:
const form = document.getElementById('submitForm');<form action='...' method='POST' enctype="multipart/form-data">
Your <form> element does not have an id, so you cannot use getElementById to reference it.
You either need to add an id to your form:
<form action='...' method='POST' enctype="multipart/form-data" id="submitForm">
or use querySelector to reference it:
const form = document.querySelector("form");
NB: If you have multiple <form> elements in your page, querySelector will only return the first one.
