Webflow sync, pageviews & more.
NEW
Answers

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?

In Webflow, you can assign custom data-attributes to buttons using the Webflow Designer. Here's how you can achieve this and set the input value through JavaScript when a button is clicked:

  1. Step 1: Create a Button in Webflow
    Using the Webflow Designer, add a button element to your page or section. You can style it however you like, and make sure to give it a class name for easy targeting. For this example, let's assume the class name is "custom-button".
  2. Step 2: Assign a Data-Attribute
    Select the button and open the Settings panel on the right-hand side. Scroll down to the "Attributes" section and click the "+ Add Attribute" button. Enter a name for your data-attribute, let's say "data-value", and set its value accordingly. You can repeat this process for multiple buttons, providing different data-values if needed.
  3. Step 3: Set Input Value Using JavaScript
    To set the input value when a button is clicked, you'll need to write a JavaScript function. There are several ways to achieve this, but let's assume you have a contact form input with the class name "contact-input".

In your JavaScript code, you can add an event listener to the buttons with the class name "custom-button". When one of these buttons is clicked, the function will be triggered, allowing you to set the input value based on the button's data-attribute. Here's an example code snippet:

```javascript
document.addEventListener("DOMContentLoaded", function() {
var buttons = document.querySelectorAll(".custom-button");
var inputElement = document.querySelector(".contact-input");

buttons.forEach(function(button) {
button.addEventListener("click", function() {
var buttonValue = button.getAttribute("data-value");
inputElement.value = buttonValue;
});
});
});
```

Make sure to replace ".custom-button" with the actual class name you used for your buttons and ".contact-input" with the class name of your contact form input. The code above fetches the data-value attribute of the clicked button and sets it as the value of the specified input element.

That's it! Now, when a user clicks one of the buttons, the corresponding data-value will be set as the value of the contact form input field. You can adjust this technique to accommodate different scenarios or requirements within your project.

Rate this answer

Other Webflow Questions