I’m developer, and I need to prevent form submission, then do some stuff, and if some conditons are well then submit the form. How I can prevent the form submission vis JS?
I’m trying to addEventListener and using e.preventDefault and e.stopPropagation but i can’t stop the submit. This is my code:
let form = document.querySelector(".klaviyo-form form");
form.addEventListener('submit', stop_submit);
functionstop_submit(e){
e.preventDefault();
e.stopPropagation();
}
Hello @xabi Since Klaviyo Forms does not use Submit events, the only way to check this is if the button is clicked and there are not errors in the form submission.
If you want to do other operations when the form is submitting you can use this code. This won’t prevent the form submission but you can perform any other operation along with the submission.
function checkElementExists(selector, callback) {
const element = document.querySelector(selector);
if (element) {
console.log(`Element ${selector} found immediately`);
callback(element);
} else {
console.log(`Element ${selector} not found. Starting observer...`);
watchForElement(selector, callback);
}
}
function watchForElement(selector, callback) {
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === "childList") {
const element = document.querySelector(selector);
if (element) {
console.log(`Element ${selector} found after watching`);
observer.disconnect();
callback(element);
return;
}
}
}
});
observer.observe(document.body, {
childList: true,
subtree: true,
});
}
// Example usage
function elementFound(element) {
console.log("Element found:", element);
let klaviyoForm = document.querySelector("form.klaviyo-form");
const subscribeButton = document.querySelector(".go3894874857"); // this is class for button
// Check if the form and button are available
if (klaviyoForm && subscribeButton) {
// Add an event listener to the form's button
subscribeButton.addEventListener("click", function (event) {
// Prevent the default button action
event.preventDefault();
const ErrorButtonDiv = document.querySelector(".go3298969293"); // this is the class of errors like this field is required
if (!ErrorButtonDiv) {
// Log the message to the console
console.log("Form is now submitted"); // perform your action when there is no error and form button is clicked
}
});
}
}
// Call this function to start checking/watching for an element