首页 > 解决方案 > 如何从 HTML 模式对话框中获取函数返回

问题描述

下面的代码创建了一个带有 HTML 模式对话框的下拉列表。这段代码工作得很好,但我想修改它以通过第一个名为 ( getFormreturn) 的函数从表单中获取提交的值。

例如:

var valueFromForm = getForm();
console.log("valueFromForm"); //Expected to print what the user selected on the form

代码现在如何工作:

  1. getForm使用 HTML 自定义对话框创建 HTML 服务
  2. sheetNames从另一个电子表格中获取所有工作表名称,并使用 HTML 中的工作表名称构建一个下拉列表
  3. 用户从下拉列表中选择并提交一个元素后,然后myFunction调用functionToRunOnFormSubmit
  4. functionToRunOnFormSubmit将提交的值从表单写入单元格。

代码.js:

function getForm() {
  try {
    var output = HtmlService.createHtmlOutputFromFile('HTML_Menu');
    SpreadsheetApp.getUi().showModalDialog(output,'Select source');
  }
  catch(err) {
    Logger.log(err);
  }
}

function getSheets() {
  try
  {
    var ss = SpreadsheetApp.openById("1tC95-rc1rXzM4VA87IPB_8FNPjQtP3zn9HfOBJtoC5U");
    var names = sheetnms(ss);
    return names;
  }
 catch(err){
    Logger.log(err);
 } 
}

function functionToRunOnFormSubmit(fromInputForm) {

  console.log(fromInputForm);

  var ss = SpreadsheetApp.getActive();
  ss.getSheetByName("test").getRange(1, 1).setValue(fromInputForm.Class);

  return fromInputForm.Class;
};

function sheetnms(ss){return ss.getSheets().map(function(x) {return x.getName();});}

HTML_Menu.html:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <form>
      <select name="Class" id="class-selector" autofocus="autofocus" autocorrect="off" autocomplete="off">
      </select>
      <input type="submit" value="Submit" onclick="myFunction(this.parentNode)">
      </form>
      <p id="addDeck"></p>
      <script>
      (function () { google.script.run.withSuccessHandler(sheetNames).getSheets(); }());
      function sheetNames(names) {
        var select = document.getElementById("class-selector");
        for( var i=0; i<names.length; i++ ) {
          var option = document.createElement("option");
          option.text = names[i];
          select.add(option);
        }
      }
      function myFunction(obj) { // Modified
        var x = document.getElementById("class-selector").value;
        document.getElementById("addDeck").innerHTML = x;
        google.script.run // Modified
          .withSuccessHandler(() => google.script.host.close())
          .functionToRunOnFormSubmit(obj);
      }
    </script>
  </body>
</html>

标签: javascripthtmlformsgoogle-apps-scriptmodal-dialog

解决方案


推荐阅读