简体   繁体   中英

Populating a Select Box with Data from Google Sheet

I have a Google site and am currently using the following script to populate my select box with data from the google sheet that is serving as my database:

<? var stringified = getData(); ?>
<?var data = JSON.parse(stringified)?>
    <select size="10" id="userChoice">
      <? for (var i = 0; i < data.length; i++) { ?>
       <option>
            <?= data[i] ?>
          <? } ?>
</select>

This loads the page with the select box populated with every entry in the database. I'm wondering if this is the best way to go about it. What I would really like to do is have the contents of the select box be a little more dynamic.

I wrote out a script to filter through (by date) the contents of the Google Sheet, but I can't quite figure out how to have those filtered results show up in the above select box. I've tried several possible solutions, but keep hitting road blocks with them. Below is the function on the client side that passes the dates to the server side (note that I realize nothing in the below scripts would pass the data back to the select box. This is just to show how I am filtering through the data):

//Takes the dates that were entered into the first two date pickers and sends them over to the server side stringified. The server side then uses these dates to filter out jobs not within the given time period.
function dateFilter(){
var date = {};

//dates pusehd into array
date[0] = document.getElementById("startDate").value;
date[1] = document.getElementById("endDate").value;

//array stringified
var dates = JSON.stringify(date);//Convert object to string

google.script.run
  .getData2(dates);

Then here is the code that filters through the database on the server side:

function getData2(dates) {
  var ss = SpreadsheetApp.openById('1emoXWjdvVmudPVb-ZvFbvnP-np_hPExvQdY-2tOcgi4').getSheetByName("Sheet1");
  var date = JSON.parse(dates);
  var dateArray = [];

  for (var k in date) {//Loop through every property in the object
    var thisValue = date[k];//
      dateArray.push(thisValue);
  };
  var startDate = Date.parse(dateArray[0]);
  var endDate = Date.parse(dateArray[1]);
  var jobReference = [];
  var job;
  var dateCell1;
  var dateCell;

  if ((startDate==NaN) || (endDate==NaN)){

    for (var i = 2; job!=""; i++){
    job = ss.getRange(i,43).getValue();
    jobReference.push(job);
  };
  }

  else{
  for (var i = 2; job!=""; i++){
   dateCell1 = ss.getRange(i,3).getValue();
   dateCell = Date.parse(dateCell1);
    if (startDate<=dateCell&&endDate>=dateCell){
    job = ss.getRange(i,43).getValue();
    jobReference.push(job);
      Logger.log("here it is"+jobReference);
    }
          else{

          }
    }

  };

  var jR = JSON.stringify(jobReference);
        return jR;
}

Now I've tried several things, having a success handler change the line <? var stringified = getData();?> <? var stringified = getData();?> to use getData2 doesn't seem to work (it yells at me that variable I'm trying to parse is undefined on the server side). So I tried putting an if/else in that would only have it parse if the variable was != to undefined, that didn't work either. Any suggestions would be appreciated.

I figured it out! This is functional, but perhaps not best practices, so if someone has any input, feel free to chime in.

So the first bit of code on the client side for the select box I left the same.

The next bit, where I send the dates over to the server side was changed to this:

function dateFilter(){
var sdate = document.getElementById("startDate").value;
var edate = document.getElementById("endDate").value;

google.script.run.withSuccessHandler(dateSuccess)
  .getData2(sdate,edate);

}

So, since it was only two variables I took out the part that pushed it to an array. This eliminated the problem of parsing on the server side and thus having an undefined variable. I also added a success handler.

The server side code was left essentially the same, however I did change the for loop slightly. Instead of having it loop through the database until it found a blank cell in a particular column, I added var last = ss.getLastRow(); and had it loop though until i<= last . This kept the code from timing out on me.

Next I added the function I used for the success handler:

function dateSuccess(jobs){
document.getElementById('userChoice').options.length = 0;

var data = JSON.parse(jobs)

for (var i = 0; i < data.length; i++) {
          var option = document.createElement("option");
option.text = data[i]
var select = document.getElementById("userChoice");
select.appendChild(option);

         } 
}

Works like a charm!

Scriptlets ie <? ?> <? ?> are compiled and run when the page is created using execute function. They are not for dynamic modification of the web page. To modify the options based on a server returned data, in this case from getData(). You would do something like this

Firstly you set your google.script to call modifyoptions function on success

google.script.run.withSuccessHandler(modifyOptions)
  .getData2(dates);

The above will code will automatically pass the return value of getData2 ie Jr value to modifyOptions function

    function modifyOptions(jobReference){
    var selOpt = document.getElementById("userChoice")
    selOpt.innerHTML =""                      // Remove previous options
    var options = ""              
    var data = JSON.parse(jobReference)
       for (var i = 0; i < data.length; i++) {
         options += "<option>"+data[i] +</option>   //New string of options based on returned data
       }

    selOpt.innerHTML = options                //Set new options

}

You can find a working example of how to modify the select-options in javascript here

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM