简体   繁体   English

使用Google表格中的数据填充选择框

[英]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: 我有一个Google网站,当前正在使用以下脚本,用作为数据库的Google表格中的数据填充选择框:

<? 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. 我写了一个脚本(按日期)筛选Google表格的内容,但我不太想知道如何在上面的选择框中显示这些筛选结果。 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();?> <? 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). <? var stringified = getData();?>使用getData2似乎不起作用(它对我大喊我试图解析的变量在服务器端未定义)。 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. 因此,我尝试将if / else放入其中,仅当变量为!=到undefined时才进行解析,但这也不起作用。 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. 服务器端代码基本上保持不变,但是我确实稍微更改了for循环。 Instead of having it loop through the database until it found a blank cell in a particular column, I added var last = ss.getLastRow(); 我没有让它遍历数据库直到在特定列中找到一个空白单元格,而是添加了var last = ss.getLastRow(); and had it loop though until i<= last . 并且让它循环直到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. 当使用execute函数创建页面时, <? ?>被编译并运行。 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(). 要基于服务器返回的数据(在本例中为getData())修改选项。 You would do something like this 你会做这样的事情

Firstly you set your google.script to call modifyoptions function on success 首先,您将google.script设置为在成功时调用ModifyOptions函数

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 上面的代码将自动将getData2的返回值即Jr值传递给ModifyOptions函数

    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 您可以在此处找到如何修改javascript中的select-option的有效示例

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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