Webflow sync, pageviews & more.
NEW

How can I correctly assign this function to a specific Webflow form on a page with the class "dashboard-form" using JavaScript?

TL;DR
  • Assign your function by targeting form.dashboard-form in a DOMContentLoaded event listener.
  • Use form.addEventListener("submit") to run your custom function on submit, optionally using event.preventDefault() based on whether you want to override Webflow’s default behavior.

To assign a custom JavaScript function to a specific Webflow form with the class "dashboard-form", you need to wait for the DOM to load and then add your function to the appropriate form event.

1. Identify the Form Element

  • Make sure the form has a class name of "dashboard-form" in Webflow Designer.
  • Webflow wraps forms in a <form> element, so the class should be applied directly to that <form> element, not just a wrapper.

2. Use JavaScript to Target the Form on Page Load

  • Add this script at the end of the <body> under Page Settings > Before tag, or through Page Custom Code.
document.addEventListener("DOMContentLoaded", function () {  const form = document.querySelector("form.dashboard-form");  if (form) {    form.addEventListener("submit", function (event) {      event.preventDefault(); // Optional: prevent actual submission      myCustomFunction(form);    });  }});

3. Define Your Custom Function

  • Create the function named myCustomFunction anywhere above or within the same script tag.
function myCustomFunction(formElement) {  // Your custom logic, e.g., data parsing, validation, API calls, etc.  console.log("Form submitted:", formElement);}

4. Alternate: Use Webflow’s w-form Wrapper

  • Webflow often adds the class w-form to the outer container, and uses the form tag inside it.
  • You can still target with querySelector("form.dashboard-form") if that class is applied directly to the form element.

5. Avoid Conflicts with Webflow Native Behavior

  • If you want to run your function in addition to the native Webflow form functionality, do not use event.preventDefault().
  • If you want to replace Webflow’s form submission (e.g., to use AJAX), then you must include event.preventDefault().

Summary

To assign a function to a Webflow form with class "dashboard-form", use document.querySelector("form.dashboard-form") inside a DOMContentLoaded event, and attach your function using addEventListener("submit"). This ensures the script runs only when the form exists and is fully loaded.

Rate this answer

Other Webflow Questions