Several use cases can lead to a need to dynamically place and update the options of a Select field based on an attribute from a CMS collection. In this article, we will see how to set up this feature on our Webflow site.
This tutorial will help you set up a dynamic select field based on a CMS collection. At Elias, we need to offer the user to select a job from the list of jobs in our CMS collection. We will therefore set up together a form that will contain a Select field, which itself will draw its values (<option>) from our database.
Several methods, each as simple as the other, exist to implement this feature. Thank you Webflow ;)
The first method is to add custom code before our page tag<Body/>.
First, we will need to add two classes to the following elements:
Once the classes are added, here is the bit of custom code you will need to add for the magic to happen. Go to the settings of your Webflow page and copy the following code there:
<script>
$ ('.select-text') .each (function () {
var s = $ (this) .text ();
$ ('.select-item') .append ('' +s+ '<option value="'+s+'">'</option>);
})
</script>
This code will allow you to find your select element on your page and fill it with all the CMS elements whose name contains the class '.select-item'.
You can imagine that a feature so practical, so used by the Webflow community, and so quick to implement will have necessarily interested our friends at Finsweet.
They have therefore set up a 3-step tutorial, just as simple as the custom code javascript method.
<!-- [Attributes by Finsweet] CMS Select -->
<script async src="https://cdn.jsdelivr.net/npm/@finsweet/attributes-cmsselect@1/cmsselect.js"></script>
All you have to do is publish your site, and that's it!
It only took you a few minutes to set up a very practical feature on your Webflow site. You will now be able to use any field from any of your CMS collections to fill in a Select field in your forms.
For more Webflow Tips and Tutorials, do not hesitate to visit our Blog or to ask us your question directly on elias.studio/contact