【问题标题】:Dynamic Dropdown List in HTML form using Google App Script使用 Google App Script 的 HTML 表单中的动态下拉列表
【发布时间】:2019-05-15 03:58:33
【问题描述】:

经过长时间的寻找(我最近一直在生活和呼吸 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


    【解决方案1】:

    这个修改怎么样?

    修改脚本:

    • form 标记处没有 onload 事件。
      • 在这个修改后的脚本中,我修改为&lt;body onload="addList()"&gt;
    • 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 端的脚本工作正常。

    参考资料:

    【讨论】:

    • 感谢您的建议。我已经操纵脚本以遵循概述的修改;但是,仍然没有生成列表选项。也许,问题在于 addList() 函数??
    • @Alex Boothe 对于给您带来的不便,我深表歉意。在我的环境中,我可以确认修改后的脚本有效。所以我无法理解你现在的情况。那么为了正确理解你目前的情况,能否提供你目前的脚本?并且请提供在getList() 返回的值。如果可以,请将其添加到您的问题中。
    【解决方案2】:

    试试这个;

    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;
    }
    

    【讨论】:

      【解决方案3】:

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

      返回值 使用成功处理程序返回的值不能返回字符串以外的任何值。所以,解决这个问题的方法(在另一个 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>

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

      【讨论】:

      • 感谢您发布您的答案。我正在尝试使其工作,但无法填充下拉列表。您的代码中是否缺少 .getEventList 函数?我没有看到它,并且 subing .getList 也不起作用。你能发布完整的工作样本吗?这是我正在研究的一个更大难题的一部分。谢谢。
      • JQuery 只是把它搞砸了。如果您找到解决方案,请分享。
      猜你喜欢
      • 2017-10-08
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 1970-01-01
      相关资源
      最近更新 更多