Webflow sync, pageviews & more.
NEW

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 a data-value attribute to each button in Webflow with the desired value.
  • Assign a unique ID to the form input, then use JavaScript to transfer the button's data-value to the input field on click.

You want to assign a data attribute to buttons in Webflow and use JavaScript to set a form input’s value when a button is clicked. Here's how to do it step-by-step.

1. Assign a Data Attribute to Each Button

  • Select each button inside the Webflow Designer.
  • Go to the Settings panel (gear icon).
  • Under Custom Attributes, add:
  • Name: data-value (or whatever name you need)
  • Value: The content you want to pass (e.g., "Support", "Pricing", etc.)

2. Give Your Form Input a Unique Selector

  • Select the input field in your form where you want to insert the value.
  • Go to the Element Settings or Style panel.
  • Give it a unique ID (e.g., "topic-input") so you can target it with JavaScript.

3. Add JavaScript to Handle Button Click

  • Go to your Webflow Page Settings or add an Embed element at the bottom of the page.
  • Paste this JavaScript inside the <script> tag (in Page Settings, paste it in the Before body tag section):
<script>  document.addEventListener('DOMContentLoaded', function () {    const buttons = document.querySelectorAll('[data-value]');    const input = document.getElementById('topic-input');    buttons.forEach(button => {      button.addEventListener('click', function () {        const value = this.getAttribute('data-value');        input.value = value;      });    });  });</script>
  • This script:
  • Waits for the DOM to load.
  • Finds all buttons with the data-value attribute.
  • On button click, reads the value and puts it into your input field.

Summary

Assign a data-value attribute to each button, give your form input a unique ID, and add simple JavaScript to listen for button clicks and populate the form. This ensures your form field is pre-filled with the appropriate value before submission.

Rate this answer

Other Webflow Questions