My product/dataset has mysteriously disappeared and I can’t link my dropdown to a collection on my page through the normal way.
I have tried to use some simple code to create dropdown options and values, but I can’t get it to work.
Ideally, I am looking for a solution that allows my users to navigate to a URL based on a value selected in the dropdown.
Here is my code:
$w . onReady ( function () {
// Write your JavaScript here
$w ( “#dropdown1” ). options = [
{ “label” : “All Meals” , “value” : “https://www.littlelunchbox.co.uk/collections/kids-meals” },
{ “label” : “Picky Eater Friendly” , “value” : “https://www.littlelunchbox.co.uk/collections/kids-meals” },
{ “label” : “Hot Meals” , “value” : “https://www.littlelunchbox.co.uk/collections/hot-meals” }
{ “label” : “Cold Meals” , “value” : “https://www.littlelunchbox.co.uk/collections/cold-meals” }
];
// To select an element by ID use: $w(‘#elementID’)
import wixLocation from ‘wix-location’ ;
$w ( “#dropdown1” ). onChange ( ( event , $w ) => {
let page = event . target . value ; // new page name selected
let path = “/” + page ; // create path to local page
wixLocation . to ( path );
});
// Click ‘Preview’ to run your code
});
How to work with dropdowns connected to databases?
Your Setup:
- You have a dropdown on your page: → ID: “#dropdown1”
- You have a DATABASE: —> DB-ID: “My-Collection”
- Where you have stored all your links in a certain DB-FIELD: → FIELD-ID: “url”
Now lets create & fill the dropdown…
import wixData from 'wix-data';
$w.onReady(async function() {
const allUserItems = await get_Data("My-Collection"); console.log(allUserItems);
create_UniqueDropdown(allUserItems, "url", "dropdown1");
});
function create_UniqueDropdown(items, dbfield, dropdown) {
const uniqueTitles = getUniqueTitles(items); $w(dropdown).options = buildOptions(uniqueTitles);
function getUniqueTitles(items) {const titlesOnly = items.map(item => item[dbfield]); return [...new Set(titlesOnly)];}
function buildOptions(uniqueList) {return uniqueList.map(curr => {return {label:curr, value:curr};});}
}
That means, all you have to do now is…
-
Creating a Collection/Database which is called “My-Collection” (of course you can change the name, but do not forget to change the name also inside CODE).
-
Generating /Creating a Database-Field → “url” ← (of course you also can change the name/id of this db-field, but do not forget to change it also in your code).
-
Adding a dropdown onto your wished page, calling it → “#dropdown1”<–, or however you want (do not forget to…).
-
Copy&Paste this code to your page.
-
Enjoying the RESULT!
Have fun and good luck!
And do not forget to like it, if you realy liked it 