Hi!
I am struggling with a task which I thought would be simple to accomplish. I am new to Wix so I searched through the forum and code examples but I could not quite get any example, unfortunately. Hope anyone could help me, please.
- I have a dropdown field on my page (“dropdownmenu”).
- I am populating the options of the dropdown box through a query (note: the dropdown box is not connected to a database because I need to query and filter the table to avoid duplicated entries)
- Then, I would like that the dropdown box shows one specific option (e.g., $w(“#dropdown”).value = my_selected_option).
I thought I can use the .value method but somehow it seems that when below code $w(“#dropdownmenu”).value = selected_menu2 is running, the dropdownfield is still not properly setup. I think I do not quite understand how the onReady logic should work, is there some sync issue to take into account?
Thanks for your help!
This is my code:
import {session} from ‘wix-storage’;
import wixData from “wix-data”;
$w.onReady( function () {
wixData.query(“Menuprices”)
.ascending(“title”)
.find()
.then( (res) =>{
const uniqueFieldValues = getUniqueFieldValues(res.items, “title”);
$w(‘#dropdownmenu’).options = buildOptions(uniqueFieldValues);
console.log(“Dropdown Initialised!”);
}, (error) => {
console.log(error);
});
// the session value “selected_menu” is set on another page and then this page, where the
// code here is given, opened
const selected_menu2 = session.getItem(“selected_menu”);
// the console log outputs a defined value for selected_menu2
console.log(selected_menu2);
// THIS HERE DOES NOT WORK
$w(“#dropdownmenu”).value = selected_menu2;
$w(“#dropdownmenu”).resetValidityIndication();
});
// remove duplicates
function getUniqueFieldValues(items , field) {
const FieldValuesOnly = items.map(item => item[field]);
return [… new Set(FieldValuesOnly)];
}
function buildOptions(uniqueList) {
return uniqueList.map(value => {
return {label:value, value:value};
});
}