There is a popular Wix code snippet most of the Wix code community uses thanks to Nayeli and Totally codeable platform but the problem started is when the code is repeatedly use.
Why you shouldn't repeat the code? What is DRY(Don't Repeat Yourself)? 1. It will be easy to maintain the code. 2. Improve the performance of the site To know more about the uses of DRY, Check this thread from stack exchange
In this example you can set the dropdown options as many you want just adding one more line ( Without rewriting the whole function again )with the detail about the collection name , dropdownPropertyId and the column (filed Key) of that database
uniqueDropdown('DatabaseName1' , 'dropdown2' , 'fieldKey');
Youtube link - Conditional Filtering Dropdowns Wix Code Example
Paste this code on a public file to reuse this function anywhere in the site and to organize the code 1. Create a public file
2. Name it as a template.js
3. Paste the following code below
//in template.js import wixData from 'wix-data'; export async function uniqueDropdown(collectionName,dropdownName,fieldKey,FilterKey,FilterValue) { $w("#" + dropdownName).disable(); $w("#" + dropdownName).value = ''; var query = wixData.query(collectionName); if (FilterKey) { query = query.contains(FilterKey, FilterValue); } let result = await query.ascending(fieldKey).limit(1000).find(); const uniqueTitles = getUniqueTitles(result.items); $w("#" + dropdownName).options = buildOptions(uniqueTitles); $w("#" + dropdownName).enable(); function getUniqueTitles(items) { const titlesOnly = items.map(item => item[fieldKey]); return [...new Set(titlesOnly)]; } function buildOptions(uniqueList) { return uniqueList.map(curr => { return { label: curr, value: curr };}); } }
4. Now you can call this function on any site
//page code
import { uniqueDropdown } from 'public/template'; $w.onReady(()=>{ //State dropdown setting unqiue value from the Database uniqueDropdown("myCollection","dropState","state"); //Filter city dropdown when the state dropdown change $w('#dropState').onChange(()=>{ let state = $w('#dropState').value; uniqueDropdown("myCollection","dropCity","city", "state", state); }); });