Introduction to Google Apps Script: Automate Your Workflows and Boost Productivity

Handling User Input with Forms

Section 5

User Interfaces with HTML Service

Introduction to Google Apps Script: Automate Your Workflows and Boost ProductivityUser Interfaces with HTML Service

In this section, we'll explore how to create interactive web apps with Google Apps Script that allow users to submit information. This is crucial for building tools that collect data, trigger actions, or customize workflows. We'll achieve this by leveraging HTML forms and the power of Google Apps Script's HTML Service to handle user input.

The core of handling user input lies in creating an HTML form within your Apps Script web app. An HTML form uses elements like <input>, <textarea>, and <select> to gather information from the user. When the user clicks a submit button, this data can be sent back to your Apps Script for processing.

<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <form id="myForm">
      <label for="name">Your Name:</label><br>
      <input type="text" id="name" name="name"><br><br>
      <label for="email">Your Email:</label><br>
      <input type="email" id="email" name="email"><br><br>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

To make this HTML accessible via Google Apps Script, you'll typically have an index.html file and a corresponding Code.gs file. The Code.gs file will have a function that returns the HTML content. For example, the doGet(e) function is commonly used for web apps.

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

Now, how do we get that form data back to our Apps Script? We use client-side JavaScript within our HTML file to capture the form submission and send the data to the server-side Apps Script. This involves adding an event listener to the form and using the google.script.run API.

<html>
  <head>
    <base target="_top">
    <script>
      function handleFormSubmit(formObject) {
        google.script.run.processForm(formObject);
      }
    </script>
  </head>
  <body>
    <form id="myForm" onsubmit="handleFormSubmit(this); return false;">
      <label for="name">Your Name:</label><br>
      <input type="text" id="name" name="name"><br><br>
      <label for="email">Your Email:</label><br>
      <input type="email" id="email" name="email"><br><br>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

The onsubmit="handleFormSubmit(this); return false;" attribute on the form is key. It calls our handleFormSubmit JavaScript function, passing the form object itself (this). The return false; prevents the browser's default form submission, which would refresh the page.

チャプターへ戻る