在Apps脚本功能中获取html文本框的值

时间:2013-05-13 15:18:19

标签: javascript html textbox google-apps-script

这里出了点问题,我从其他有类似问题的人那里得到的所有建议似乎都没有用。

我有两个文件:google脚本中的myPage.html和myCode.gs。我已经将html文件部署为Web应用程序,并且我已经找到了(如果有帮助)如何使用'submit'按钮的onclick事件来触发myCode.gs文件中的emailTech函数就好了。

现在我想将html文件中文本框中的值插入从onClick事件调用的电子邮件中。我尝试了document.getElementById('textBoxId').value,但是我收到以下错误“参考错误:”文档“未定义。”什么给出了?

myPage.html文件:

<html>
<head>
    <title>Test Page</title>
</head>
<body>
<input type="button" onClick="google.script.run.emailTech();" value="Submit" />

<input type="text" value=" " id = "textBox" name = "textBox" />
</body>
    <script type="text/javascript">
    </script>
</html>

myCode.gs文件:

  function doGet() {
  return HtmlService.createHtmlOutputFromFile('myPage');
}

function emailTech(){

  var nameBox = document.getElementById('textBox').value;
  var message = "This is the text box value" + nameBox;
  MailApp.sendEmail("123@xyz.com", "This is the subject", message );
}

1 个答案:

答案 0 :(得分:8)

错误消息正确 - 在您的Apps脚本功能emailTech()中,范围内没有名为document的变量。

您有两种不同的方式来部署Apps Script WebApps。由于您正在使用HTML服务(并且您的用户界面是html文件),因此您无法使用UI服务方法(如getElementById())来访问输入值。所以,你会做一些不同的事情。

要将提交按钮和输入字段绑定在一起,请使用<form>标记中的表单。提交按钮仍然具有onclick功能,但现在它将是嵌入在HTML中的javascript函数,它将把表单中的所有输入传递给emailTech()函数。

在您的应用程序脚本端处理程序中,您将收到表单输入作为对象,表单中的字段作为键值对。关键是来自该字段的name

this answer中描述了一般解决方案。这是适合您代码的版本。我遗漏了Arun所说的成功和失败处理。在进行现实生活中的部署之前,你应该构建错误检查。

Code.gs

function doGet() {
  return HtmlService.createHtmlOutputFromFile('myPage');
}

function emailTech(form){

  var nameBox = form.techEmail;
  var message = "This is the text box value" + nameBox;
  MailApp.sendEmail("email@somewhere.com", "This is the subject", message );

}

myPage.html下

<html>

    <head>
        <title>Test Page</title>
    </head>

    <body>
        <form>
            <input type="text" value=" " name="techEmail" />
            <input type="button" onClick="formSubmit()" value="Submit" />
        </form>
    </body>
    <script type="text/javascript">
        function formSubmit() {
            google.script.run.emailTech(document.forms[0]);
        }
    </script>

</html>