Webflow sync, pageviews & more.
NEW

How can I use Webflow to show/hide divs based on a user's selection in a form?

TL;DR
  • Create distinct divs for each form option and assign unique classes or data-option attributes.
  • Add custom JavaScript to listen for form changes, then show or hide divs by matching the selected value with data-option attributes.

To show or hide divs based on a user's form selection in Webflow, you'll need to use Webflow Interactions or a bit of custom JavaScript for dynamic behavior.

1. Structure Your Form and Divs

  • Add a form field like a Select dropdown or Radio Buttons using the Form Block.
  • For each selectable option, create a separate div you want to show or hide.
  • Give each div a unique and clear class name or ID (e.g., div-option-a, div-option-b).

2. Add Custom Attributes (Optional for Simplicity)

  • For easier targeting, you can use custom attributes such as data-option="A", data-option="B" on your target divs to match with the form values.

3. Add Custom JavaScript in Page Settings

  • Go to Page Settings > Before tag section and paste the following simplified script:
<script>  document.addEventListener('DOMContentLoaded', function () {    const selectField = document.querySelector('select[name="your-field-name"]'); // Replace with actual field name    const optionDivs = document.querySelectorAll('[data-option]');    function updateDivs(selectedValue) {      optionDivs.forEach(div => {        if (div.getAttribute('data-option') === selectedValue) {          div.style.display = 'block';        } else {          div.style.display = 'none';        }      });    }    if (selectField) {      updateDivs(selectField.value); // Initialize based on default      selectField.addEventListener('change', function () {        updateDivs(this.value);      });    }  });</script>
  • Important: Replace "your-field-name" with the actual input field name.

4. Set Initial Visibility in Webflow

  • Set all target divs to display: none (in the Style panel) if you don’t want them visible on load.
  • Make sure visibility is controlled programmatically using the div.style.display override.

5. Test Your Form Behavior

  • Preview the site in Webflow or publish it.
  • Select different options in the form to confirm the correct div shows while others hide.

Summary

To show/hide divs based on a user's form selection in Webflow, create separate target divs for each option, tag them clearly (e.g., with data-option), and use custom JavaScript to toggle their visibility based on the user's input value.

Rate this answer

Other Webflow Questions