I'm trying to confirm the email using contact form 7 within wordpress and I did do :
<script>
document.addEventListener("DOMContentLoaded", function () {
const form = document.querySelector("form");
const email = document.querySelector("input[name='email-380']");
const confirmEmail = document.querySelector("input[name='email-381']");
const emailError = document.getElementById("email_error");
document.addEventListener("submit", function (e) {
if (email.value.trim() !== confirmEmail.value.trim()) {
e.preventDefault();
emailError.style.display = "block";
confirmEmail.focus();
return false;
window.history.back();
} else {
emailError.style.display = "none";
}
});
});
</script>
the script is working as expected..but the issue is the form is submitted
even though I set return false;
could anyone please help, to prevent the form to submit .
thanks
I'm trying to confirm the email using contact form 7 within wordpress and I did do :
<script>
document.addEventListener("DOMContentLoaded", function () {
const form = document.querySelector("form");
const email = document.querySelector("input[name='email-380']");
const confirmEmail = document.querySelector("input[name='email-381']");
const emailError = document.getElementById("email_error");
document.addEventListener("submit", function (e) {
if (email.value.trim() !== confirmEmail.value.trim()) {
e.preventDefault();
emailError.style.display = "block";
confirmEmail.focus();
return false;
window.history.back();
} else {
emailError.style.display = "none";
}
});
});
</script>
the script is working as expected..but the issue is the form is submitted
even though I set return false;
could anyone please help, to prevent the form to submit .
thanks
- You can't cancel the form submission via javascript. Here's an example of using the "Abort" in Contact Form 7. stackoverflow/questions/73475064/… – Howard E Commented Mar 12 at 18:54
1 Answer
Reset to default 0You're adding the submit event listener to document, not to the form itself. Try attaching the event listener directly to the form like below :
const form = document.querySelector("form.wpcf7-form");
form.addEventListener("submit", function (e) {
Check the corrected code below :
document.addEventListener("DOMContentLoaded", function () {
const form = document.querySelector("form.wpcf7-form");
const email = document.querySelector("input[name='email-380']");
const confirmEmail = document.querySelector("input[name='email-381']");
const emailError = document.getElementById("email_error");
form.addEventListener("submit", function (e) {
if (email.value.trim() !== confirmEmail.value.trim()) {
e.preventDefault();
emailError.style.display = "block";
confirmEmail.focus();
} else {
emailError.style.display = "none";
}
});
});