Filter checkboxgroup fed from collection

Hello,

I am building a custom form in EditorX (not using Wix Forms) for my Website and am trying to use some custom elements.

I need to Collect Data on “Department” and then “job titles” - Department is a choice Via a dropdown menu, Job Titles os a multiple choice tick box.

I need to Filter the Tick box options by which department is chosen in the Department Dropdown.

I am currently using this code to populate the multiple tick box options from a database, now I need to Filter based on department chosen (also fed from a database.) both then need to be entered into a Third Database. - Can anyone help me with how to build the filter?

The Job titles Database has a column for Job title and a column for “applicable department.

import wixData from ‘wix-data’;

$w.onReady( function () {

wixData.query("JobTitles") 
.find() 
.then((results)=> { 

    **let**  optionsArray =[]; 
    results.items.forEach(element => { 
        
        optionsArray.push({label:element.title, Value:element.title}); 

    }) 

    $w('#checkboxGroup2').options = optionsArray; 
}) 

. catch ((err)=> {
let errormsg = err;
})

To be clear there are currently three Databases

  1. Job Titles (a list of job titles with the departments they are applicable to)

  2. Department’s (a list of departments)

  3. Freelist - a collection of the user input data from the form.

Can anyone help?

Here is the Code that worked for anyone with similar Requirements

$w.onReady(function () {

  // Set up the initial query to fetch all job titles
  let query = wixData.query("JobTitles");

  // Populate the dropdown menu with the available department values
  query.distinct("department")
    .then((results) => {
      let optionsArray = results.items.map((element) => {
        return { label: element, value: element };
      });
      optionsArray.unshift({ label: "All", value: "All" });
      $w('#dropdown1').options = optionsArray;
    })
    .catch((err) => {
      console.log(err);
    });

  // Set up the event handler for the dropdown menu
  $w('#dropdown1').onChange(() => {

    // Get the selected value from the dropdown menu
    let selectedValue = $w('#dropdown1').value;

    // Modify the query based on the selected value
    if (selectedValue === "All") {
      query = wixData.query("JobTitles");
    } else {
      query = wixData.query("JobTitles")
        .eq("department", selectedValue);
    }

    // Run the query and populate the checkbox group with the results
    query.find()
      .then((results) => {
        let optionsArray = results.items.map((element) => {
          return { label: element.title, value: element.title };
        });
        $w('#checkboxGroup2').options = optionsArray;
      })
      .catch((err) => {
        console.log(err);
      });
  });
});