Having trouble getting the Html onload function to work in Google Sheets App Script?

I'm working with google sheets and I'm in the process of creating a document to track employees who are currently out of the office. I have added a menu option that allows me to remove employee data, which triggers the opening of a sidebar containing an HTML form (View my project image). My goal is to populate a dropdown list in this form with the names of current employees.

I have written the necessary code to extract the required data:

function removeAnyone() {
  var html = HtmlService.createHtmlOutputFromFile('RemoveAnyone');
  SpreadsheetApp.getUi()
    .showSidebar(html);
}

function getList() {
  var headerRows = 1;
  var sheet = SpreadsheetApp.getActive().getSheetByName("Data");
  var range = sheet.getRange(headerRows + 1, 1, sheet.getMaxRows() - headerRows, 1);
  var arrayValues = range.getValues();
  return arrayValues;
}

Next, we move on to my HTML code, where I am attempting to populate the dropdown list using a for loop within the header:

<!DOCTYPE html>
<html>

<head>
  <base target="_top">
  <script>
    function addOption_list() {

     document.getElementById("output").innerHTML = "test";

    var options = google.script.run.getList();

    for (var i = 0; i < options.length; ++i;) {
      var optn = document.createElement("OPTION");
      optn.text = options[i];
      optn.value = options[i];
      document.myForm.selectEmployee.options.add(optn);

      }
    }
  </script>
</head>

<body onload="addOption_list()">
  <form id="myForm" onsubmit="submitForm(this)">
    <select id="selectEmployee">
      <option>Choose an employee</option>
     </select>
  </form>
  <div id="output"></div>
</body>

</html>

To initially test if the function is being called, I included a div in the body and had the function change its value to "test". However, it seems like the function is not being executed.

I also attempted using window.onload (shown below), but unfortunately, that did not yield any positive results either:

window.onload = function {

     document.getElementById("output").innerHTML = "test";

     var options = google.script.run.getList();

     for (var i = 0; i < options.length; ++i;) {
       var optn = document.createElement("OPTION");
       optn.text = options[i];
       optn.value = options[i];
       document.myForm.selectEmployee.options.add(optn);

      }
    }

Any advice or guidance you could provide would be greatly appreciated!

Answer №1

google.script.run doesn't directly return values when used in Google Apps Script. To retrieve values, you should use withSuccessHandler. Keep in mind that the data obtained through getValues() is a two-dimensional array. Consider the following script modification:

Adjusted Code :

<!DOCTYPE html>
<html>

<head>
  <base target="_top">
  <script>
    window.onload = function() {
      google.script.run.withSuccessHandler(addOption_list).getList();
    }
    function addOption_list(options) {
      document.getElementById("output").innerHTML = "test";
      var select = document.getElementById('selectEmployee');
      for (var i in options) {
        var optn = document.createElement('option');
        optn.value = options[i][0];
        optn.text = options[i][0];
        select.appendChild(optn);
      }
    }
  </script>
</head>

<body>
  <form id="myForm" onsubmit="submitForm(this)">
    <select id="selectEmployee">
      <option>Choose an employee</option>
     </select>
  </form>
  <div id="output"></div>
</body>

</html>

Additional Resources :

If I misunderstood your query, I apologize for any confusion.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Regular Expressions in Express.js Routes

Is there a way to extract a specific value from my URL using Express? For example, my URL structure is as follows: host/:value.schema I need to retrieve the value from this URL. Here's an example: host/horse.schema (In this case, the value wo ...

Retrieving and storing state in session storage with React

My webpage features a sidenav with expansion panels that can be opened and closed. I am currently working on setting the state to keep track of which expansion panel is open. However, when I click on one of the items in the sidenav, I get redirected to a ...

How can I achieve auto-refresh functionality in SQLite using PHP and JavaScript without refreshing the entire page

I am currently working with a straightforward php code that retrieves data from a SQLite database by using the query "$query ="Select A from B"". The process works smoothly, and upon updating the SQLite database, I can refresh the page to display the new d ...

Angular front-end rendering with Rails backend integration

Currently, I am working on a medium-sized Rails application and my latest endeavor is to integrate Angular into the system. After reviewing several tutorials, it appears that the most common method for fetching initial data and displaying the first view in ...

Go through each item in the array and change its properties

When retrieving data from the database, I receive the following information: "Data": [{ "mainData": [{ "_id": ObjectId("5ab63b22d012ea2bc0bb7e9b"), "date": "2018-03-24" }], "files": [ { "_id": ObjectId("5ab63b22d012ea2bc0bb7e9d"), ...

Which specific event in NextJS is triggered only during the initial load?

I am working on a NextJS app and I want to implement an initial loading screen that only appears during the first load. Currently, the loading screen pops up not only on the initial load but also whenever a link is clicked that directs the user back to the ...

Concentrate on the disappeared div element following the AJAX request

Encountering an unusual issue here that has me a bit puzzled. In one of my DIV elements, I have included several links which trigger an AJAX call (using jQuery) upon being clicked. The server (Controller) then responds with HTML content, specifically a JS ...

Eliminate the commas when listing Google Places types

I am currently utilizing the Google Places API and came across these code snippets at https://developers.google.com/maps/documentation/javascript/examples/place-search-pagination. var map, placesList; function initialize() { var pyrmont = new google.ma ...

Choice of product variations as a package

I am currently working on a project and here is the data structure I have set up for options and combinations: Options: "options": [ { "id": "96ce60e9-b09b-4cf6-aeca-83f75af9ef4b", "position": 0, "name": & ...

Preventing the removal of a choice by disabling it in the selector

I have a unique selector that is designed like this: <select id="patientSelector"> <option disabled selected style='display: none;' id="select0"> New Patients to Come</option> <option id="select1"></opt ...

Using AngularJS to display a targeted row in a table

I am currently working with a basic table and using ng-repeat to display rows in the table. I have a specific requirement where I want to show an additional row when a regular row is clicked. This additional row should contain custom markup in just one co ...

Tips for including a subquery in query results using axis

I have a query for the objects table using an id. Then, I want to query the same table with the id from my result and add it as a new property. Does that explanation make sense? app.get(`/details`, (req, res) => { const { id } = req.query; connectio ...

Easily accessible jQuery tabs with the option to directly link to a specific tab

I currently have tabs set up on my webpage. The code for these tabs is as follows: $('ul#tabs li a').click(function(){ var id = $(this).attr('id'); var counter = 1; $("ul#tabs a.current").removeClass('cur ...

Guide on utilizing Nextjs middleware for directing users to sub-domain according to their IP address

I've been struggling to effectively implement NextJs's middleware for redirecting users from a specific country to another web domain. I've encountered some issues with my setup: Main domain: https://www.example.com sub-domain: src/middle ...

Steps to exit browser in WebDriver Sampler in JMeter and halt execution

I have been attempting to close the browser in my Selenium Jmeter last sampler thread, but I keep encountering the following error: INFO c.g.j.p.w.s.WebDriverSampler: WebDriver has been quit. 2024-02-01 22:53:24,989 ERROR c.g.j.p.w.s.WebDriverSampler: Sess ...

Encountered a NodeJS error while attempting to locate information in a mongo DB: UnhandledPromiseRejectionWarning

In my MEAN stack application, I am working on implementing a login feature that includes social login functionality. When a new user attempts to log in using Facebook, I need to verify if their Facebook account is already registered in my MongoDB database. ...

Having trouble configuring React-Router-Dom correctly

Hey there, I'm currently working on a project using react-router-dom. It seems like I may have missed a step in following the instructions because I'm encountering the following issues: bundle.js:1085 Warning: Failed prop type: The prop `history ...

React Ant Design: Toggle Visibility of Columns

Seeking a method to toggle the visibility of columns for the Table Component in Ant Design. The goal is to include a checkbox next to each column name. When unchecked, the column should be hidden. In my previous experience with react-table, accomplishing ...

Unexpected Results: React Multiline MUI Text Box Fails to Show Intended Content

In the process of developing a React application, I have come across a requirement to implement a multiline text box for editing job advertisements. The text box should initially display a default value containing dynamic placeholders such as [displayTitle ...

The v-for directive is displaying my list in a single row with multiple columns instead of in a single column with multiple rows

Can someone please assist in rendering my list as shown below: A B C The current rendering looks like this: 1: A 2: B 3: C Below is the code snippet: To-Do List: <input type="text" class = "todo" placeholder = "Next Item" v-on:keyup.enter="add ...