javascript - 在 Apps 脚本函数中获取 html 文本框的值

标签 javascript html textbox google-apps-script

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

我有两个文件:google 脚本中的 myPage.html 和 myCode.gs。我已经将 html 文件部署为 Web 应用程序,并且我已经弄清楚(在帮助下)如何使“提交”按钮的 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 );
}

最佳答案

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

您有两种不同的方式混合部署 Apps 脚本 Web 应用程序。由于您使用的是 HTML 服务(并且您的用户界面是一个 html 文件),因此您不能使用 UI 服务方法(如 getElementById() )来访问输入值。所以,你会做一些不同的事情。

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

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

通用解决方案在this answer中有描述。 .这是适合您的代码的版本。我省略了 Arun 展示的成功和失败处理。当然,在现实生活中部署它之前,您应该建立错误检查。

代码.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 );

}

我的页面.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>

关于javascript - 在 Apps 脚本函数中获取 html 文本框的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16525553/

相关文章:

javascript - 使用jquery在栏内淡入淡出

jquery - 如何在 jQuery 中用另一个元素包装现有元素?

html - 具有自定义边框的 CSS 表格

WPF 字体 : Why are some characters missing?

javascript - 如何查找数据类型而不是页面类型

javascript - Jquery HTML 选择标签附加重复本身

javascript - 在 HTML 可排序表中动态隐藏/显示行数据

javascript - 在 Bootstrap 下拉切换中触发 jQuery

c# - 如何将文本框上的自动完成链接到数据库表? C# 2.0

c# - 使用 Viewbox 缩放包含标签和文本框的网格