Search code examples
javascripthtmlgoogle-apps-scriptgoogle-sheetssidebar

Can I use HTML sidebar to call a function in Google Appscript?


I need to use a sidebar to get some variables and print then in the last line of a sheet, using AppScript. So, I was trying to use this code:

Sidebar.HTML

<!DOCTYPE html>
<html>

<head>
  <base target="_top">
</head>

<body>
  <p>Name: <input type="text" name="txtName" /></p>
  <p>Date: <input type="text" name="txtDate" /></p>
  <p>Value: <input type="text" name="txtValue" /></p>
  <button onclick="doSomething()"> submit </button>
  <script>
    function doSomething() {
      google.script.run.withFailureHandler(myFunction(document.getElementById("txtName", "txtDate", "txtValue").value))
    }
  </script>

</body>

</html>

Code.js

function myFunction(name = "", date = "", value = "") {
  var ss = SpreadsheetApp.getActive()
  var sheet = ss.getSheetByName("1")

  var lr = sheet.getLastRow() + 1

  sheet.getRange(lr, 1).setValue(name)
  sheet.getRange(lr, 2).setValue(date)
  sheet.getRange(lr, 3).setValue(value)
}

function openDialog() {
  var html = HtmlService.createHtmlOutputFromFile("Sidebar");
  html.setTitle("Form");
  SpreadsheetApp.getUi().showSidebar(html);
}

But it don't worked. When I click on the button nothing happen. I'm new in HTML, so, what can I do to fixit?


Solution

  • Looks like you got almost everything right except for 2 things, both in the Sidebar.HTML file —

    1. Given that you're using getElementById, you also need to add an id tag in the input fields
    2. The implementation of google.script.run.withFailureHandler seems to be a bit off. You can read through the official documentation for more info
      • you can also skip using withFailureHandler altogether by just using google.script.run.myFunction(...)

    Here's the final working code for reference —

    <!DOCTYPE html>
    <html>
    
    <head>
      <base target="_top">
    </head>
    
    <body>
      <p>Name: <input type="text" name="txtName" id="txtName" /></p>
      <p>Date: <input type="text" name="txtDate" id="txtDate" /></p>
      <p>Value: <input type="text" name="txtValue" id="txtValue" /></p>
      <button onclick="doSomething()"> submit </button>
      <script>
        function doSomething() {
          google.script.run.withFailureHandler()
          .myFunction(document.getElementById("txtName").value,document.getElementById("txtDate").value,document.getElementById("txtValue").value)
        }
      </script>
    
    </body>
    
    </html>