Dropdown to Query Database

I am trying to do something that I though should be fairly simple but I am struggling with. I have a database of departments with contact info. I want to have a dropdown of the departments that when you select the department, it shows the contact information and autofills a simple form for sending an email with the departments email address. I cannot figure out how to get this to work or find a similar example.

2 Likes

I have a similar problem to Jess with a double filtered dropdown (the code below). My issue is that the dropdowns are showing what is in the database but it is not running the filter to take out the dropdown options that don’t apply…

$w.onReady( function () {
});
//from gender
export function gender2_change(event, $w) {
$w(“#SAsport”).enable();
sportFilter()();
//the code for this event is here:
}
function sportFilter (){
$w(“#indexsport”).setFilter( wixData.filter()
.eq(“gender”, $w(“#gender2”).value)
);
}

//from sport selection
export function SAsport_onchange(event, $w) {
$w(“#SApositionbysport”).enable();
positionFilter()();
}
function positionFilter (){
$w(“indexpositions”).setFilter( wixData.filter()
.eq(“sport_name”, $w(“#SAsport”).value)
);
}

Hi all:

First you need to add a dropdown to your page which I assume you have done.
Then you need to connect the data collection containing the field you need in your drop down to a dataset on the page.

Next you click on the dataset icon of the dropdown list element

and connect to the dataset using the DropDown connection settings


Once you have configured the drop down you can then create an onChange() handler to react to items selected from the drop down.

So if your dropdown element is called $w(‘#dropDown1’) you need to set up $w(‘#dropDown1’) .onChange(event) as follows:

$w('#dropDown1').onChange(event) {
    // Get the scoping selector
    let scopeSelector = $w.at(event.context);
    // Get the dataset record to manage
    let selectedItem = scopeSelector('#datasetName').currentItem;
    
    // OR if the drop down is a join table get the drop down value 
    // and search the join table for the record you need
    //
    let joinId = $w('#dropDown1').value; 
    // Set up query on $w('#datasetName') to find a record that matches joinId
    ...
}

Reference points:

Hope this helps
Steve

Hi,
In addition to stcroppe’s answer, you should also check out this article about sending emails.

Good luck :slight_smile:

Hi again, the dropdown menus were always working as normal. My problem is that the dropdowns are still displaying all of the options in the database instead of filtering out and displaying only the options based on the selection above. It is probably something small, but I must not be using the filtering function properly (see original submission code). Thanks in advance for your help!

Hi Docentz:

The code you posted above has at least one bug. $w(‘indexPositions’) should be $w(‘#indexPositions’) assuming that is the correct element name.

Also so without seeing your page it’s hard to understand what you are trying to achieve and assess other possible bugs.

If you post the url for the page you are having problems with then It will be easier to give more specific help.

Steve

Hi Steve, thanks for that, I updated the code with the #…here is the site (internal code: https://editor.wix.com/html/editor/web/renderer/edit/77c68210-9e89-4c11-9838-24b6ee852763?metaSiteId=85950e3e-3567-4869-9e8f-18170ff1d0c0&etpa=12f1fbab-8b9d-3002-87b5-2972897e8314)
The website page in question: https://www.mybrakt.com/my-brackets

Hi Docentz:

Well your major problem is that you have a few errors in your javascript code.
The developer console is showing:

There was an error in your script
and also

Error: The element selector function (usually $w) cannot be used before the page is ready
These are essentially the same error and when encountered essentially stop your code from executing.
So what are the errors? Here goes:

  1. You have too many onReady functions
    You really only need one onReady function for Page code and one for Site code otherwise you will end up with confusing results.

  2. You need to use the $w scope selector inside the onReady function or an event handler
    Both of your onReady functions are empty and so don’t do much for you.

$w.onReady(function() {
     <---------- code you need to execute to set up your page goes here 
});

You have a lot of code that follows your second onReady function call. When the code is loaded in the browser it trips over the first statement:

let sport = $w(‘SAsport’).value;
Since this code is using $w element selector for the SAsport element before the onReady has fired then an error is generated because Wix hasn’t finished loading the page elements and the element probably doesn’t exist yet. The simple fix for this is to delete the onReady code on lines 5 and 6 and delete the code on line 31

});

and add it after the code that follows onReady on line 117.

  1. You have two SAsport onChange handlers
    One is called

export function SAsport_onchange(event, $w)
The other is called

$w(‘#SAsport’).onChange(function () {
Each does something different so may not produce the results you are looking for. better to have one function and make sure it does what you want :-).

  1. Your call to sportfilter has two sets of parentheses
    sportfilter()(); should be sportfilter();

  2. Your call to positionFilter has two sets of parentheses
    positionFilter()(); should be positionFilter();

  3. Redundant .then() call after fetch function call
    You have two .then() calls following the fetch in:

$w(‘#button1’).onClick(…
The second is redundant as it will only repeat the first console.log call (at least in as far as it will
display the json property again).

.then(function(httpResponse) {          
    console.log(JSON.stringify(httpResponse)); <-------+
    return httpResponse.json();                        |
})                                                     | 
                                               These do similar things
// This code VVVVVVV is redundant                      |
.then(function(output){                                |
    console.log(JSON.stringify(output));       <-------+
})

Here is the code modified per these comments. But I am not promising it will work because I don’t have access to your Wix Editor. The link above doesn’t do it. I would need contributor access to your page. However all things being equal this should help move you further forward than you are at the moment :wink:

Steve


// For full API documentation, including code examples, visit http://wix.to/94BuAAs
import {fetch} from 'wix-fetch';
import wixData from 'wix-data';

//Delete this code...
//$w.onReady(function () { 
//});
//from gender
export function gender2_onchange(event, $w) {
    $w("#SAsport").enable();
    sportFilter(); // Remove second pair of ()
}

function sportFilter (){
    $w("#indexsport").setFilter( 
        wixData.filter()
        .eq("gender", $w("#gender2").value)
    );
}

//Redundant onchange function call removed
//export function SAsport_onchange(event, $w) {
//    $w("#SApositionbysport").enable();
//    positionFilter(); // Remove second pair of ()    
//}

function positionFilter (){
    $w("#indexpositions").setFilter( 
        wixData.filter()
        .eq("sport_name", $w("#SAsport").value)
    );
}

$w.onReady(function () { 
// Remove this --> });

  let sport = $w('#SAsport').value;
  console.log($w('#SAsport').options);
  console.log($w('#SAsport').value);
  console.log("http://www.docentz.com/positions/"+$w('#SAsport').value);

  $w('#SAsport').onChange(function () {
      // ADD CODE FROM Other onchange function commented out above
      $w("#SApositionbysport").enable();
      positionFilter(); // Remove second pair of ()
       
      // ORIGINAL CODE
      sport = $w('#SAsport').value;
      //fetch("http://www.docentz.com/positions/"+sport, {method: "GET"})
      fetch("http://www.docentz.com/positions/basketball"+sport, 
           {method: "GET"}
      )
      .then(function(httpResponse) {
          console.log(JSON.stringify(httpResponse));
          return httpResponse.json();
      });    
  })

/*
  $w('#input13').onChange(function () {
    fetch("http://www.docentz.com/majors", {method: "GET",
        headers: {"Content-Type": "text/plain"},
        body: JSON.stringify({"q": $w('#input13')})
    })
    .then(function(httpResponse) {
      console.log(JSON.stringify(httpResponse));
      return httpResponse.json();
    })
    .then(function(output){
      console.log(JSON.stringify(output));
    })
  })
  */

  $w('#button1').onClick(function () {
      let sa_item;
      let b_item;

      sa_item = $w('#dataset2').getCurrentItem();
      console.log(JSON.stringify(sa_item));
      b_item = $w('#dataset1').getCurrentItem();
      console.log(JSON.stringify(b_item));

      let inputs = {
                "last_name": sa_item["lastName"],
                "first_name": sa_item["firstName"],
                "email": sa_item["email"],                      // How is this email different from the bracket email?
                "gender": b_item["gender"],                     // Why would the gender not be with the student athlete info instead of the bracket?
                "high_school": b_item["currentSchool"],         // Why would this not be in the student athlete info?
                "resident": b_item["currentResidence"],         // Why would this not be in the student athlete info?
                "majors": b_item["major"],                      // Do we only want to ask about 1 major and not multiples?
//                "majors": "39",                                 // Placeholder until dropdown works
                "states": b_item["statePreference"],            // Should be able to pick all
                "year": b_item["grade"],                        // Why not name this year instead of grade? Fitting for transfers too. Does not have year transfer
                "sport": b_item["sport"],
                "size": b_item["collegeSize"],
                "counselor_name": b_item["counselorName"],
                "counselor_email": b_item["counselorEmail"],
                "gpa": b_item["gpa"],
                "college_type": b_item["collegeType"],
                "interested": b_item["inContact"],              // Multiples?
                "sat": b_item["sat"],
                "act": b_item["act"],
                "alma_mater": b_item["almaMater"],              // Multiples?
                "division": "All",                              // MISSING!! Defaulting to all for now
                "phone": "",                                    // MISSING!! Leaving empty
                "coach_name": "",                               // MISSING!! Leaving empty
                "coach_email": "",                              // MISSING!! Leaving empty
                "position": "forward",                          // MISSING!! Need to know the sport position
                "result_id": b_item["_id"],
                "student_id": sa_item["_id"]
                };
                                                                // SA Name should probably be SA ID so that you can relate it back to the SA db easily

    fetch("http://www.docentz.com/submit", 
        {
            method: "POST",
            headers: {"Content-Type": "application/x-www-form-urlencoded"},
            body: JSON.stringify(inputs)
        }
    )
    .then(function(httpResponse) {
        console.log(JSON.stringify(httpResponse));
        return httpResponse.json();
    })
    // Removing following code as it is redundant
    //.then(function(output){
    //    console.log(JSON.stringify(output));
    //})
    .catch(err => console.log(err));
  });
});  // <------- add this to complete the $w.onReady() call.