首页 > 解决方案 > 如何从自定义 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>

标签: javascripthtmlgoogle-apps-scriptgoogle-sheets

解决方案


我相信你的目标和情况如下。

  • 您想将 textarea 的值发送到addNewMethodGoogle 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,请在输入值后从文本区域中移除焦点。

推荐阅读