使用 Google App Script 以 HTML 形式动态下拉列表

问题描述 投票:0回答:4

经过长时间的寻找(我最近一直生活在 StackOverflow 中),我想我应该把我的问题告诉大家。

我还是 Google Script 的新手,所以请耐心等待。 我正在尝试编写一个动态下拉列表作为 HTML 表单的输入。我的希望是获取列表以使用谷歌表格中的值填充选项。返回数组值的函数 getList 按预期工作,但将选项标签及其值添加到列表的函数失败...

查看我下面的内容,如果您有任何见解或可以引导我走向正确的方向,请告诉我。谢谢!!

//basic function that builds the form using indexEvent.html as the template
function doGet(e) {
     return HtmlService
     .createTemplateFromFile('index')
     .evaluate()
     .setSandboxMode(HtmlService.SandboxMode.NATIVE);
}

//Simple function to find the wanted sheet by it's independent ID
function getSheetById(id) {
   return SpreadsheetApp.getActive().getSheets().filter(
      function(s) {return s.getSheetId() === id;}
   )[0];
}

//Gets existing values in Column "B" and lump into 1-D array
function getList() {
    var ss = SpreadsheetApp.openById('sheet ID');
    var sheet = getSheetById(240411081); 
    var list  = sheet.getRange(2, 2, sheet.getLastRow()-1, 1).getValues();
    var values  = list.toString().split(",");
    
    return values;
}
<!DOCTYPE html>
<html>
<head>
  <base target="_top">
</head>
  <body>
    <form id="Form" onload="addList()">
      <div>
        <label for="List">Select Value:</label><br>
        <input list="list" name="list" placeholder="Choose Value" required> -->
          <datalist id="dropdownList">
          <!-- 
          This is where I am trying to dynamical add <option> tags 
          EXAMPLE:
            <option value="values[0]" />
            <option value="values[1]" />
            <option value="values[2]" />
            ... and so on
          -->
          </datalist>
      </div>
    </form>
  </body>
  
  <script>
    function addList() {
      google.script.run
        .withFailureHandler(onFailure)
        .withSuccessHandler(addListValues)
        .getList();
    }

    function addListValues(values) {
      var list = document.getElementById('dropdownList');   
        for (var i = 0; i < values.length; i++) {
          list.appendChild('<option value="' + values[i] + '" />');
        }
    }

    function onFailure(err) {
      alert('There was an error!' + err.message);
    }
  </script>
  
<html>
    

javascript html forms google-apps-script
4个回答
1
投票

这个修改怎么样?

修改后的脚本:

  • form
    标签处没有onload事件。
    • 在这个修改后的脚本中,我修改为
      <body onload="addList()">
  • HTML 和 Javascript 的
    datalist
    存在一些问题。
    • input
      标签处,修改为
      list="dropdownList"
    • 在 Javascript 中,当值附加到
      datalist
      时,它使用
      document.createElement("option")

修改后的脚本:

<!DOCTYPE html>
<html>
<head>
  <base target="_top">
</head>
  <body onload="addList()"> <!-- Modified -->
    <form id="Form"> <!-- Modified -->
      <div>
        <label for="List">Select Value:</label><br>
        <input list="dropdownList" name="list" placeholder="Choose Value" required> --> <!-- Modified -->
          <datalist id="dropdownList">
          <!-- 
          This is where I am trying to dynamical add <option> tags 
          EXAMPLE:
            <option value="values[0]" />
            <option value="values[1]" />
            <option value="values[2]" />
            ... and so on
          -->
          </datalist>
      </div>
    </form>
  </body>

  <script>
    function addList() {
      google.script.run
        .withFailureHandler(onFailure)
        .withSuccessHandler(addListValues)
        .getList();
    }

    function addListValues(values) {
      var list = document.getElementById('dropdownList');   
      for (var i = 0; i < values.length; i++) {
        var option = document.createElement("option"); // Modified
        option.value = values[i]; // Modified
        list.appendChild(option); // Modified
      }
    }

    function onFailure(err) {
      alert('There was an error!' + err.message);
    }
  </script>

<html>

注:

  • 在这个修改后的脚本中,假设GAS端的脚本工作正常。

参考资料:


0
投票

试试这个;

html:

google.script.run//I often put this sort of thing in the ready function or windows.load
  .withSuccessHandler(function(vA) {
    $('#sel1').css('background-color','#ffffff');
    updateSelect(vA);
  })
  .getSelectOptions();

function updateSelect(vA,id){//the id allows me to use it for other elements
  var id=id || 'sel1';
  var select = document.getElementById(id);
  select.options.length = 0; 
  for(var i=0;i<vA.length;i++)
  {
    select.options[i] = new Option(vA[i],vA[i]);
  }
}

gs:

function getSelectOptions()
{
  sortOptions();
  var ss=SpreadsheetApp.openById(getGlobal('gSSID'));
  var sh=ss.getSheetByName('Options');
  var rg=sh.getDataRange();
  var vA=rg.getValues();
  var options=[];
  for(var i=0;i<vA.length;i++)
  {
    options.push(vA[i][0]);
  }
  return vA;
}

0
投票

我发现了问题并进行了适当的修改:

返回值 使用成功处理程序的返回值不能返回字符串以外的任何值。因此,解决这个问题的方法(在另一个 StackOverflow 页面上找到)是使用:

气体:

// GAS 

function getList() {
    var ss = SpreadsheetApp.openById('sheet ID');
    var sheet = getSheetById(240411081); 
    var list  = sheet.getRange(2, 2, sheet.getLastRow()-1, 1).getValues();
    var values  = list.toString().split(",");
    
    return JSON.stringify(values); //Modified
}

JSON stringify 函数将数组转换为字符串值,返回是合法的。在 HTML 中,您必须解析 JSON 来重组数组。否则,其他脚本将起作用。

注意:我添加了 JQuery 来简化调用 HTML 元素

HTML:

<body onload="addList();">
 <form id="form">
    <div>
       <input list="List" name="eventList" placeholder="-- Select Event --" required>
          <datalist id="List"> 
             <option>Loading...</option>       
          </datalist>
    </div>     
 </form>
 </body>

 <script>
  function addList() {
         google.script.run.withSuccessHandler(writeList).withFailureHandler(onFail) 
           .getEventList();
  }

  function writeList(list) {
      var dropdown = $("#List");
      dropdown.empty();
      var options = JSON.parse(list); //Modified
      var sortOpt = options.sort();
         if (options.length > 0) {
             for ( var i = 0; i < sortOpt.length; i++) {
                 if (i == 0) {dropdown.append('<option>CUSTOM</option>');}
                   dropdown.append('<option>' + sortOpt[i] + '</option>');
             }
         }
   }
  
  function onFail() {
    alert("This action failed to complete.");
  }
 </script>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> 
 </script>
 </html>

感谢那些为我的问题提供解决方案的人。


0
投票

2024 年,我找到了解决我自己问题的方法。效果很好,但这条线对我不起作用:

var 下拉菜单 = $("#List");

必须使用:

var list = document.getElementById('List');

工作功能:

function addListValues(values)
{     
    var list = document.getElementById('List');  
    var options = JSON.parse(values);
    for (var i = 0; i < options.length; i++) {
        var option = document.createElement("option"); 
        option.value = options[i]; 
        list.appendChild(option); 
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.