I am trying to use this code to redirect the user to a new page when the form is submitted and validated, but it does not seem to be working. When I submit the form, I see the console.log output test for a brief moment in the console, but the page does not redirect. Why is this happening and how can I fix it?
(function () {
'use strict'
var forms = document.querySelectorAll('.needs-validation')
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
} else{
window.location = "newpage.html";
#console.log("test")
}
form.classList.add('was-validated')
}, false)
})
})()
CodePudding user response:
Adding the event.preventDefault()
before window.location
does solve the problem like suggested by @RoryMcCrossan
(function () {
'use strict'
var forms = document.querySelectorAll('.needs-validation')
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
} else{
event.preventDefault()
window.location = "newpage.html";
}
form.classList.add('was-validated')
}, false)
})
})()
CodePudding user response:
I hope this will work
(function () {
'use strict'
var forms = document.querySelectorAll('.needs-validation')
Array.prototype.slice.call(forms)
.forEach(function (form) {
form.addEventListener('submit', function (event) {
event.preventDefault()
if (!form.checkValidity()) {
event.stopPropagation()
} else{
window.location = "newpage.html";
}
form.classList.add('was-validated')
}, false)
})
})()