Skip to content

Instantly share code, notes, and snippets.

@cspags
Last active September 25, 2023 16:17
Show Gist options
  • Save cspags/60d04387ee4a225ff89ba618bfedc7e3 to your computer and use it in GitHub Desktop.
Save cspags/60d04387ee4a225ff89ba618bfedc7e3 to your computer and use it in GitHub Desktop.
Webflow - Reset a form to it's original state after it is submitted, instead of showing the success message
$(function() {
/*** START SCRIPT CONFIG ***/
// Replace with value for your form. ie. "#your-form-id" or ".your-form-class"
var FORM_SELECTOR = ".recipe-form";
// Do you want to hide the success message after the form is submitted?
var HIDE_SUCCESS_MESSAGE = false;
// Do you want the success message to show above the form?
var SUCCESS_MESSAGE_ABOVE_FORM = true;
/*** END SCRIPT CONFIG ***/
var resetCustomElement = function(customElement) {
var inputElement = customElement.nextSibling;
if (inputElement.checked) {
customElement.classList.add("w--redirected-checked");
} else {
customElement.classList.remove("w--redirected-checked");
}
};
var resetForm = function(form, successDiv) {
// Reset the inputs in the form
form.reset();
// Reset custom checkboxes
document.querySelectorAll(".w-checkbox-input--inputType-custom").forEach(resetCustomElement);
// Reset custom radio buttons
document.querySelectorAll(".w-form-formradioinput--inputType-custom").forEach(resetCustomElement);
// Show the form
form.style.display = "block";
// Hide Success Message
if (HIDE_SUCCESS_MESSAGE) {
successDiv.style.display = "none";
}
};
var form = document.querySelector(FORM_SELECTOR);
var successDiv = form.nextSibling;
if (!HIDE_SUCCESS_MESSAGE && SUCCESS_MESSAGE_ABOVE_FORM) {
// Move the form last so that the success message appears before it
form.parentElement.appendChild(form);
}
// Create an observer to run our resetForm function when Webflow hides our form after submission
var observer = new MutationObserver(function(mutations) {
if (form.style.display === "none") {
resetForm(form, successDiv);
}
});
// Listen for when the style attribute of our form changes
observer.observe(form, { attributes: true, attributeFilter: ["style"] });
});
@meaganalixburns
Copy link

@Hollandk709, this code works BUT you need to use the ID of the form, not a class. Webflow puts the form block within a DIV using the classes specified in Webflow. This tripped me up a bit, as I initially specified a class, but since it's a class on a div and not the actual form block, the script does nothing. Using the ID of the form directly targets the form block — script works flawlessly after that. Thanks @cspags!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment