How can I give buttons a data-attribute in Webflow and then set the input value through JavaScript when one of the buttons is clicked, so that the value is already in the contact form?

TL;DR
  • Add data attributes like data-value="yourValue" to each button in Webflow's Element Settings for unique input correlation.
  • Insert an input field in the contact form with a unique ID for JavaScript targeting.
  • Use JavaScript in Webflow's Custom Code section to add event listeners that set the input field value, matching the button's data-value upon a click event.

To add data attributes to buttons and set the corresponding input values through JavaScript in Webflow, you will follow these steps:

1. Add Data-Attributes to Buttons

  • Access your Webflow project and navigate to the page with the buttons you want to modify.
  • Select a button and open the Element Settings panel (gear icon).
  • Scroll to Custom Attributes and add new attributes such as data-value="yourValue" to each button. Ensure that each button has a unique data-value that corresponds to the input value you want to set.

2. Add an Input Field to the Contact Form

  • Navigate to the contact form within the same page.
  • Add an input field where the value should be pre-filled. Make sure to give it a unique ID for easy targeting in your JavaScript.

3. Write JavaScript to Set Input Value

  • Open Webflow Designer and go to the Page Settings for the page where your form is located.
  • Go to Custom Code and enter the JavaScript code within the <script> tags in the Footer Code section. The code should look like the following:
  • Add Event Listeners to each button. When a button is clicked, read its data-value.
  • Set the Input Value using JavaScript by targeting the input field by its ID.

<script>
  document.addEventListener('DOMContentLoaded', () => {
      const buttons = document.querySelectorAll('button[data-value]');
      const inputField = document.getElementById('yourInputId');

      buttons.forEach(button => {
          button.addEventListener('click', () => {
              const value = button.getAttribute('data-value');
              if (inputField) {
                  inputField.value = value;
              }
          });
      });
  });
</script>

Summary

Add data-attributes to each button and use JavaScript to update the input field in your contact form when a button is clicked. Ensure each button has a unique data-value, and use event listeners to set the value of the input field identified by its unique ID. By following these steps, you'll pre-fill form values based on button clicks effectively within Webflow.

Rate this answer

Other Webflow Questions