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

Using Vue.js to handle asynchronous functions with undefined variables

My Vue.js application is facing a problem where an async function is passing a variable as undefined even though it's properly defined before the function call. The async function FETCH_DATA in my Vue.js application is defined like this: async [FETCH ...

Utilizing AJAX and jQuery to dynamically load a div instantly, followed by automatic refreshing at set intervals

I am utilizing jQuery and AJAX to refresh a few divs every X seconds. I am interested in finding out how to load these divs immediately upon the page loading for the first time, and then waiting (for example, 30 seconds) before each subsequent refresh. I h ...

Create a VueJS/VuetifyJS implementation inspired by the WhatsApp swipe between tabs animation

Currently, I am utilizing the VuetifyJS framework for VueJS and I am interested in replicating the swipe between tabs transition seen in WhatsApp for Android. In WhatsApp, you have the ability to swipe left or right to view a new section as you swipe. Vue ...

Manage text, PDF, and image files in a MEAN stack app by uploading and fetching them from a MongoDB database using

I have been working on developing a piece of code that allows users to create a dynamic URL, upload a file by clicking a button on the page, and then download the same file in the same format when revisiting the URL. The functionality is similar to cl1p, b ...

jQuery - Enlarge Tree View to the level of the selected node

I am struggling to figure out how to expand the tree view up to a selected node level. If anyone has any ideas on how to accomplish this, please let me know. For instance, if we click on 'Parent d' in the 'Category list', I want to exp ...

A guide to efficiently fetch JSON data synchronously using AngularJS

Trying to fetch data from a JSON file using AngularJS results in an error due to the asynchronous nature of the call. The code moves on to the next step before receiving the data, causing issues. The $http.get method was used. $http.get('job.json&apo ...

Using jQuery, target the specific elements that have certain data attributes assigned to them

Is there a way to target elements with a specific data attribute and a unique class using jQuery? For instance, I want to select these elements: <div data-roomid="55" data-status="NoData"></div> <div data-roomid="55" data-status="Open"> ...

Oops! Looks like the connection has been abruptly cut off from the ASYNC node

Is there a way to properly close an async connection once all data has been successfully entered? Despite attempting to end the connection outside of the loop, it seems that the structure is being finalized after the first INSERT operation CODE require( ...

What is the best way to coordinate text and photos within Bootstrap?

Currently, I am working on a bootstrap website that features a slideshow with 3 photos. The jQuery function responsible for this is as follows: $(function () { $.vegas('slideshow', { backgrounds: [{ src: 'img/ph1.jpg ...

Using Javascript code to draw particles at the cursor's position and then directing those particles towards the bottom of

I found an interesting JavaScript code snippet that creates a bubble particles effect around the cursor. You can download it from https://github.com/tholman/90s-cursor-effects. However, I encountered a problem when adding certain elements inside a specifi ...

It is impossible to add a new element between two existing elements that share the same parent

I'm attempting to place an <hr> tag between the first and second .field-container. Because they have the same parent, I thought using element1.parentNode.insertBefore(element2, ...) would be the solution. However, it is not working as expected a ...

Unable to begin the previous project on my Mac, but it functions properly on Windows

After running npm i, I encountered the following error message which I am unsure how to resolve. I tried reinstalling Node.js, Python, and Pyenv, but the issue persists. Interestingly, the same version of Node.js on Windows runs the project without any p ...

When attempting to view the PDF file, it appears completely void

After spending countless hours on this task, I'm still not making any progress. My goal is to download a PDF file from my server while currently running the operation on localhost. However, whenever I open the downloaded PDF, all I see is a blank whit ...

Having an issue with displaying the country name and country code in a table using the Angular7 custom pipe

country code: "ab", "aa", "fr", ... I need to create a custom pipe that will convert a countryCode into a countryName, such as: "ab" → "Abkhazian", "ch" → "Chinese", "fr" ...

Automatically switch tabs upon pressing/scanning the Return key (using PHP, MySQL, and JavaScript)

Seeking assistance to resolve an ongoing issue that has been troubling me for the past few weeks. I am maintaining a basic web-based database to keep track of product serial numbers leaving our warehouse. The system is secure behind our firewall, so I&apo ...

Error occurred during npm build with Browserify: Module not found

When I run npm build with the following command: "build": "browserify -t [ babelify --presets [ es2015 react ] ] app/assets/app.jsx -o public/javascripts/app.js" I encounter the error message below: Error: Cannot find module 'components/maininput.j ...

Select a Date: Input for Date Selection

Is it possible to restrict the selection of certain days using HTML date input validation? Some booking websites have a feature where an interactive calendar only allows users to select specific dates for events, while others are greyed out and cannot be c ...

JavaScript allows for inserting one HTML tag into another by using the `appendChild()` method. This method

My goal is to insert a <div id="all_content"> element into the <sector id="all_field"> element using Javascript <section id="all_field"></section> <div id="all_content"> <h1>---&nbsp;&nbsp;Meeting Room Booki ...

Encountering an issue when bundling an application using electron-forge: "Unable to find solution for './→' "

Having trouble packaging my Electron application using electron-forge. It seems like the issue lies with native modules such as 'sqlite3'. Upon running the command npm run package, I encounter this error: Module not found: Error: Can't reso ...

Observable<void> fails to trigger the subscriber

I am currently facing a challenge with implementing a unit test for an Observable in order to signal the completion of a process. While there is no asynchronous code in the logout function yet, I plan to include it once the full logic is implemented. The m ...