javascript - 如何从自定义 HTML 侧边栏中更改 Google 表格单元格中的值?
问题描述
我有一个带有自定义侧边栏的 Google 电子表格。侧边栏只包含一个表单<textarea>
。使用<textarea>
脚本从表格单元格中获取值。我想通过onchange
触发器将新值从侧边栏发送到同一个单元格,或者如果用户没有更改旧值,则将旧值保留在单元格中。你可以在下面看到我所拥有的。不幸的是,它不起作用。不起作用意味着侧边栏从单元格中获取价值,但在更改后不发送新的。我不明白为什么我错了以及如何解决?
function showSidebar() {
var html = HtmlService.createHtmlOutputFromFile('Change.html')
.setTitle('Cooking method')
.setWidth(300);
SpreadsheetApp.getUi()
.showSidebar(html);
}
function addNewMethod(form_data)
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Method');
var cookingMethod = form_data.method;
sheet.getRange('A2').setValue(cookingMethod);
}
function getDefaultMethod() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('Method');
const currentMethod = sheet.getRange('A2').getValue();
return currentMethod
}
<!doctype html>
<html lang="en">
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<meta charset="utf-8">
<title>change</title>
<style>
body{
background-color: #3366CC;
}
textarea {
margin: 10px
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function()
{
google.script.run
.withSuccessHandler(updateMethod)
.getDefaultMethod();
});
function updateMethod(method_val)
{
document.getElementById('method').innerHTML=method_val;
}
</script>
</head>
<body>
<form id="mysidebar">
<div class="block form-group">
<label for="method"></label>
<textarea id="method" name="method" rows="30" cols="45">
</textarea>
</div>
</form>
<div></div>
<script>
$("method").change(function () {
google.script.run.addNewMethod(this);
}).change();
</script>
</body>
</html>
解决方案
我相信你的目标和情况如下。
- 您想将 textarea 的值发送到
addNewMethod
Google Apps 脚本。 - 当您更改 textarea 并移除焦点时,您希望将其发送到 GAS 端。
- 在这种情况下,您不使用 Google Apps 脚本库。GAS 和 HTML 文件放在容器绑定脚本的一个 GAS 项目中。
对于这个,这个修改怎么样?
首先,请检查我对您这个问题的理解是否正确。
修改后的脚本:
在这种情况下,请按如下方式修改您的 HTML&Javascript。在这个修改中,作为一个简单的修改,我没有修改你的 Google Apps Script 端。
从:$("method").change(function () {
google.script.run.addNewMethod(this);
}).change();
至:
$("#method").change(function () {
const obj = {method: $("#method").val()};
google.script.run.addNewMethod(obj);
});
- 在这种情况下,为了运行
google.script.run
,请在输入值后从文本区域中移除焦点。
推荐阅读
- tkinter - 显示意外结果的命令函数
- pyarrow - 使用数据构造表。避免创建数据框
- nginx - NGINX - 为静态文件位置添加后缀
- python - 我可以让我的 python 脚本在 arduino 串行监视器中输入命令吗?
- python - Gzip 到 base64 编码将字符添加到 JSON 字符串
- php - Symfony 4. 为什么提交的表单只是部分填充模型?
- python - 列算术
- java - AES/EAX 加密与 JCE - EAX 中的 Mac 签入失败
- javascript - 如何将对象中的字符串值转换为数字?
- api - 如何在 openapi 3.0.2 中格式化 DELETE 方法?