How can I use JavaScript to display the name of the item from the CMS collection as the 'name' field for each checkbox in Webflow? Can custom code be used to set an aria label that reads the collection item name printed on the page to the right of each checkbox in Webflow?

Published on
September 22, 2023

To display the name of the item from the CMS collection as the 'name' field for each checkbox in Webflow using JavaScript, you can follow these steps:

  1. Add a custom code block: In the Webflow Designer, you can add a custom code block to the page where you want the checkboxes to be displayed. To do this, click on the '+ Add' button in the left-hand panel, select 'Symbol' from the dropdown menu, and then choose 'Custom Code' from the next dropdown menu.

  2. Assign a class or ID to the checkbox elements: In the custom code block, you can assign a unique class or ID to each checkbox element. This can be done by wrapping each checkbox in a <div> or <label> element and providing a specific class or ID.

  3. Access the CMS collection data: In the custom code block, you can use JavaScript to fetch the relevant data from your CMS collection. This can be done by using Webflow's JavaScript API to make a request to the Webflow CMS API and retrieve the necessary data.

  4. Set the checkbox name and aria-label attributes: Once you have the data from the CMS collection, you can loop through each checkbox element and set the 'name' attribute to the corresponding item name from the collection. Additionally, you can set the 'aria-label' attribute to the same value to provide an accessible label for screen readers.

Here's an example of how you can achieve this using JavaScript:

var checkboxes = document.querySelectorAll('.checkbox-class'); // Replace '.checkbox-class' with the specific class or ID you assigned to the checkboxesfetch('/your-cms-collection-url') // Replace '/your-cms-collection-url' with the actual URL of your CMS collection data  .then(response => response.json())  .then(data => {    checkboxes.forEach((checkbox, index) => {      checkbox.name = data.items[index].name;      checkbox.setAttribute('aria-label', data.items[index].name);    });  });

Make sure to replace '/your-cms-collection-url' with the actual URL of your CMS collection data.

By following these steps, you can dynamically set the name and aria-label attributes of the checkboxes using JavaScript and display the name of the item from the CMS collection as the 'name' field for each checkbox in Webflow.

Additional Questions:

  1. How do I add custom code to a Webflow site?
  2. Can I use JavaScript to interact with Webflow CMS collections?
  3. What is the Webflow JavaScript API?