Populating dropdown with custom function

Hi everyone,

I’m working on a Wix website using the Wix Studio Editor and trying to create a form where selecting an option from a radio button group dynamically filters and populates a dropdown menu with the appropriate options.

Here’s the issue I’m facing: When I select a category from the radio buttons, the dropdown menu should only show items related to that category. However, instead of filtering correctly, the dropdown shows all items from all categories. Additionally, if I select an option from outside the chosen category in the dropdown, nothing happens. If I select an option within the chosen category, it correctly loads the related information.

Can anyone help me identify what might be going wrong in my code? I’d appreciate any advice or examples on how to make the dropdown filter properly based on the selected radio button option. Here is my current code:

import wixData from ‘wix-data’;

$w.onReady(function () {
// Initialize the page with default county selection
initPage();
});

// Function to initialize the page
async function initPage() {
const countyCities = {}; // Cache for cities per county

// Set default selection to 'Los Angeles'
$w('#countyRadioGroup').value = "Los Angeles";

// Populate dropdown with cities for the default county
await populateCityDropdown("Los Angeles", countyCities);

// Event handler for county radio button changes
$w('#countyRadioGroup').onChange(async () => {
    const selectedCounty = $w('#countyRadioGroup').value;
    console.log("Selected County:", selectedCounty); // Debugging: Log selected county

    // Clear the dropdown before populating it with new options
    $w('#cityDropdown').options = []; // Clear current options

    // Populate the dropdown with cities from the selected county
    await populateCityDropdown(selectedCounty, countyCities);
});

// Event handler for dropdown changes to enable the search button
$w('#cityDropdown').onChange(() => {
    $w('#searchButton').enable();
});

}

// Function to populate the dropdown with cities based on the selected county
async function populateCityDropdown(county, countyCities) {
console.log(“Populating cities for county:”, county); // Debugging: Log county

// Clear the dropdown before populating it with new options
$w('#cityDropdown').options = [];

// Check if cities for the selected county are already cached
if (countyCities[county]) {
    console.log("Using cached cities for county:", county); // Debugging: Log cache use
    $w('#cityDropdown').options = countyCities[county]; // Use cached options
    handleDropdownState(true);
} else {
    console.log("Querying cities for county:", county); // Debugging: Log querying
    // Query the collection for cities in the selected county
    const results = await wixData.query('Communities')
        .eq('County', county)  // Ensure field name matches exactly ('County')
        .ascending('Title')
        .find();

    // If cities are found, update the dropdown
    if (results.items.length > 0) {
        console.log("Cities found:", results.items); // Debugging: Log found cities
        const cityOptions = results.items.map(city => ({ label: city.Title, value: city._id })); // Use 'Title' for city names
        $w('#cityDropdown').options = cityOptions; // Populate dropdown
        countyCities[county] = cityOptions; // Cache the city options
        handleDropdownState(true);
    } else {
        console.log("No cities found for county:", county); // Debugging: Log no cities found
        $w('#cityDropdown').options = []; // Clear dropdown if no cities found
        handleDropdownState(false);
    }
}

}

// Function to handle the dropdown state and search button
function handleDropdownState(hasCities) {
if (hasCities) {
$w(‘#cityDropdown’).selectedIndex = undefined;
$w(‘#cityDropdown’).expand();
$w(‘#searchButton’).disable();
} else {
$w(‘#cityDropdown’).collapse();
$w(‘#searchButton’).enable();
}
}

You can also see what’s happening on the live site by following this link:(https://jack5267.wixstudio.io/my-site/communities-item)

Thanks in advance for your help!

Jack

Hi, user3134 !!

I browsed your site, and it’s a wonderful site with beautiful scenery that really catches the eye! :wink:

Then, I think you need to first check if the correct values are being retrieved by the query executed after the radio button is changed. Since you’re getting “all” values, it seems natural to assume that the filter part is failing. Reading your code, I personally noticed that you’re targeting fields like “Country” and “Title” in the query, but isn’t it correct to use “country” or “title” instead? The default field ID for the “Title” field in a Wix collection should be “title,” so I thought you might have mistakenly entered the display name.

Thanks for your suggestion! I’ve double-checked the dataset, and the field IDs are correctly set as title (all lowercase) and county (all lowercase). I’ve updated the code to use these exact field names, but unfortunately, I’m still experiencing the same issue.

When I select a different county from the radio button, the dropdown list is still not filtering correctly to show the cities only for that selected county. Instead, it seems to be displaying all the cities or not updating as expected.

If you have any additional insights or suggestions on what might be causing this problem, I would greatly appreciate your help!

Thanks again for your assistance!

Curretn Code:

import wixData from ‘wix-data’; // Import wixData to access collections

$w.onReady(function () {
initPage();
});

async function initPage() {
const countyCities = {}; // Cache for cities per county

// Set initial states
$w('#cityDropdown').show(); // Ensure dropdown is visible
$w('#searchButton').hide(); // Initially hide the search button

// Set default county and populate its cities
const defaultCounty = "Los Angeles";
$w('#countyRadioGroup').value = defaultCounty;
await updateCityDropdown(defaultCounty, countyCities);

// Event handler for county radio button changes
$w('#countyRadioGroup').onChange(async () => {
    const selectedCounty = $w('#countyRadioGroup').value;
    console.log("Selected County:", selectedCounty); // Debugging
    await updateCityDropdown(selectedCounty, countyCities);
});

// Event handler for city dropdown changes
$w('#cityDropdown').onChange(() => {
    const selectedCity = $w('#cityDropdown').value;
    console.log("Selected City:", selectedCity); // Debugging
    $w('#searchButton').show(); // Show the search button when a city is selected

    updateMap(selectedCity); // Update map or related elements
});

}

// Function to update the city dropdown based on selected county
async function updateCityDropdown(county, countyCities) {
$w(‘#cityDropdown’).options = ; // Clear current options
console.log(“Clearing dropdown options for new county selection.”); // Debugging

if (countyCities[county]) {
    // Use cached options if available
    $w('#cityDropdown').options = countyCities[county];
    console.log("Using cached cities for county:", county); // Debugging
    manageVisibility(true);
} else {
    console.log("Querying cities for county:", county); // Debugging
    try {
        // Query the collection for cities based on the selected county
        const results = await wixData.query('Communities')
            .eq('county', county) // Use lowercase "county"
            .ascending('title') // Use lowercase "title"
            .find();

        console.log("Query results:", results.items); // Debugging: Log query results

        if (results.items.length > 0) {
            const cityOptions = results.items.map(city => ({ label: city.title, value: city._id })); // Use lowercase "title" for display
            $w('#cityDropdown').options = cityOptions; // Populate dropdown
            countyCities[county] = cityOptions; // Cache results
            console.log("Cities found and dropdown populated:", cityOptions); // Debugging
            manageVisibility(true);
        } else {
            console.log("No cities found for county:", county); // Debugging
            manageVisibility(false);
        }
    } catch (error) {
        console.error("Error querying cities:", error); // Debugging
        manageVisibility(false);
    }
}

}

// Function to manage visibility of dropdown and button
function manageVisibility(hasCities) {
if (hasCities) {
$w(‘#cityDropdown’).show();
$w(‘#searchButton’).hide();
} else {
$w(‘#cityDropdown’).hide();
$w(‘#searchButton’).show();
}
}

// Function to update the map or other elements based on selected city
function updateMap(cityId) {
console.log(“Updating map for city ID:”, cityId); // Debugging
// Add your map update logic here
}

I see. :thinking: But the process you’re trying to implement is quite simple. If you take your time and work through it methodically, I’m sure you’ll be able to resolve the issue. In situations like this, it’s really important to verify each step based on the console.log results, making sure the program is running in the expected order and identifying where things are getting stuck.

As a first step, can you confirm whether the query results are being retrieved correctly? Check the log at console.log("Query results:", results.items). Does it show the correct values? Given your level of coding, if the query results are retrieved successfully, I believe you’ll be able to implement the rest without any issues.

Also, there’s a chance that the error might be happening elsewhere in the code, so I recommend commenting out any unnecessary code for this test and running it again in the simplest scenario to focus on troubleshooting this issue. :wink: