How can I set a default option for the select dropdown button in Webflow e-commerce using basic JavaScript lines?
TL;DR
- Inspect the dropdown to find its class or ID using Developer Tools.
- Add JavaScript in a script tag at the bottom of the page to select the dropdown, set
.selectedIndexto the desired default, and dispatch a 'change' event. - Insert the script via Page Settings or an Embed element and test it on the published site.
To set a default option for a select dropdown (e.g., product variant selector) in Webflow E-commerce, use basic JavaScript to manipulate the DOM once the page or CMS content loads.
1. Identify the Dropdown Element
- Select dropdowns in Webflow are typically rendered with the
<select>tag. - Use Developer Tools (right-click > Inspect) to find the class or ID of the select element you want to target.
Example: You might find a class like .w-commerce-commercevariantoption.
2. Write JavaScript to Set Default Option
You can use basic JavaScript code like:
- Use
querySelectororgetElementByIdto target the dropdown. - Use the
.selectedIndexor set theselectedattribute on a specific<option>.
Example Script (include in the Page Settings or an Embed block at the bottom of Body):
<script> document.addEventListener("DOMContentLoaded", function () { var dropdown = document.querySelector('.your-dropdown-class'); // Replace with actual class if (dropdown) { dropdown.selectedIndex = 1; // 0 is the first option, so use 1 for the second, and so on dropdown.dispatchEvent(new Event('change')); // Trigger change to update variant selection } }); </script>- Replace
.your-dropdown-classwith your actual dropdown class (e.g.,.w-commerce-commercevariantoption). - Adjust
selectedIndexto the position of the option you want as default.
3. Add It to Your Webflow Site
- Go to Page Settings or use an Embed component inside the desired page.
- Paste the JavaScript in a
<script>tag at the bottom of the page’s body. - Make sure it loads after the dropdown element is rendered.
4. Test Live After Publishing
- JavaScript may not run correctly in preview mode.
- Publish your site and verify the default option is selected automatically.
Summary
Use JavaScript to set .selectedIndex or .selected on the dropdown's <option> element and dispatch a change event to ensure Webflow's E-commerce system recognizes the selection. Always test on the published site for expected behavior.