Fill your HTML form effortlessly using data from Google Sheets

I am relatively new to this topic, but I'm seeking a solution to populate an Apps Script Web App HTML dropdown form with names directly from a Google Spreadsheet. At the moment, I've managed to retrieve an array of names from column A in my spreadsheet. Additionally, the "Populates Form" section of the JavaScript code effectively fills the HTML form.

However, I'm struggling to connect these two parts. I have attempted to replace the hardcoded array in the latter portion of the JavaScript code with the function getColleagueList(), as well as removing the function altogether and leaving only the variables. Unfortunately, neither of these approaches resulted in the form being populated. I believe there is a simple solution to this issue, but I'm unsure of what steps to take. Thank you for your help in advance.

<!DOCTYPE html>
<html>
<head>
</head>
  <body>


  <select id="selectColleague">
    <option disabled selected value="">
      Reviewer's Name
    </option>
  </select> 

  <script type="text/javascript">

  // Retrieves Names
  function getColleagueList() {
     var s1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Roster Import');
     var range = s1.getRange(2, 1,s1.getLastRow()-1, 1).getValues();
     return range;
  }


  // Populates Form
  var select = document.getElementById("selectColleague");
  var options = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"];
    for(var i = 0; i < options.length; i++) {
      var opt = options[i];
      var el = document.createElement("option");
       el.textContent = opt;
       el.value = opt;
       select.appendChild(el);
  }
 </script>

Answer №1

The function getColleagueList() should be implemented on the server side. It can be placed in a file called Code.gs. Afterward, you can invoke the server-side function through JavaScript using the following approach: For detailed information, please refer to this resource: https://developers.google.com/apps-script/guides/html/communication

<script>
          function onSuccess(values) {
            var select = document.getElementById("selectColleague");
            var options = values[0]; //This is a two-dimensional array
            for(var i = 0; i < options.length; i++) {
                var opt = options[i];
                var el = document.createElement("option");
                el.textContent = opt;
                el.value = opt;
                select.appendChild(el);
            }
          }

          google.script.run.withSuccessHandler(onSuccess)
              .getColleagueList();
</script>

Answer №2

@JohnSmith has provided a fantastic solution with the .gs code for the back-end. It's working flawlessly. Your web app code is also excellent, just needs a minor tweak:

    var settings = values[0]; 
    //modify it to:
    var settings = values;

This modification allows the loop to iterate through the entire array and display all the results you desire. Take a look at the updated version here: Web App

I hope this adjustment proves helpful! Wishing you the best of luck!

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

The button in my form, created using React, continuously causes the page to refresh

I tried to create a chat application using node.js and react.js. However, I'm facing an issue where clicking the button on my page refreshes the entire page. As a beginner in web development, please forgive me if this is an obvious problem. You can fi ...

What is the best way to incorporate a loading icon onto a webpage that exclusively runs JavaScript functions?

I frequently use Ajax load icons to indicate progress during ajax requests. Is there a way to achieve the same result using regular JavaScript? For instance: $('button').on('click', function(){ showLoadingIcon(); lengthyProces ...

Encountering an "undefined" error when implementing the useReducer hook in React

I'm encountering an error when using the UseReducer hook in React. Even though I have destructured the state object, I still receive this error: const [{previousOperand,currentOperand,operation},dispatch] = useReducer(reducer,{}); return ( ...

The functionality of the "Slots" prop has no impact when used on the material-ui Slider component

Trying to understand the purpose of the "slots" prop in relation to customizing how inner components like track and thumb are rendered within the Slider component. A basic example of rendering a Slider component is shown below const marks = [ { value: 0 ...

What is the best way to organize large amounts of data into an array?

I am currently working on developing a unique version of wordle using javascript and html. In order to do this, I require a comprehensive list of all possible wordle words stored in an array format. Although I have the words listed within a document contai ...

The AJAX request and UPDATE query are not working as expected

Currently, I am attempting to use an UPDATE query with an AJAX call to update a player's division by sending it to the update_divisions.php file. The process involves selecting a user from one select box and choosing the desired division from another ...

Adapting CSS styles according to the height of the viewport

Goldman Sachs has an interesting webpage located here. One feature that caught my eye is the header that appears as you scroll down, with squares changing from white to blue based on the section of the page. I'm curious about how they achieved this ef ...

Populate an HTML table using a JavaScript array containing objects

Greetings, fellow coders! I am new to the coding world and this community, and despite my efforts in searching for a solution, I couldn't find exactly what I was looking for. So, here is my question: I have an array structured as follows: const arr ...

Using React Refs to Trigger the video.play() Method - A Step-by-Step Guide

Is there a way to use a ref in order to trigger video.play()? Currently encountering an error: preview.bundle.js:261916 Uncaught TypeError: _this2.videoRef.play is not a function Take a look at my component: import React from 'react'; import s ...

Leverage D3 force simulation as a functional programming tool

Currently, I am utilizing d3-force for collision detection in my project: function customLayout(nodesWithCoordinates) { const simulation = forceSimulation(nodesWithCoordinates) .force('collide', forceCollide(4.5)) .stop() .tick(300 ...

What is the process for inserting an image into a table using el-table and el-table-column components in Vue.js while utilizing ui-elements?

I'm new to Vue.js and successfully built a basic table using the ui-element. The el-table element was utilized for constructing the table, with columns displayed using el-table-column and prop (see code below). Now, I want to incorporate images/avatar ...

Implementing automatic selection mode in Kendo MVC grid

Seeking to modify the SelectionMode of a Kendo MVC Grid, I aim to switch from single to multiple using Javascript or JQuery upon checkbox selection, and revert back when the checkbox is unchecked. Is this feasible? Additionally, I am successfully binding a ...

Using AngularJS to retrieve JSON data with the HTTP module

I am a beginner in the world of angularjs and I need some guidance. Below is the code I have written: <!DOCTYPE HTML> <html ng-app="myapp"> <head> <meta charset="utf-8"> <title>Angularjs project</title> <script type= ...

Refresh MySQL database using AJAX

In my form, there are both a submit button and a close button. When a user enters information and clicks the submit button, an answer is posted and saved in the database. If the user chooses to click the close button instead, the entry in the database will ...

How can I retrieve data from a script tag in an ASP.NET MVC application?

I'm struggling to figure out how to properly access parameters in a jQuery call. Here is what I currently have: // Controller code public ActionResult Offer() { ... ViewData["max"] = max; ViewData["min"] = min; ... return View(paginatedOffers ...

Center an absolutely positioned div using CSS

What is the best way to position an absolute div at the center? <div class="photoFrame">minimum width of 600px, positioned absolutely</div> jQuery var screenWidth = $(window).width(); $('.photoFrame').css({'margin-left': ...

What are the appropriate situations to utilize Q.defer versus using Promise.resolve/reject?

I've been working with nodejs and I'm curious about when to use Q defer over Promise.resolve/reject? There are numerous examples of both methods, such as: // using Q defer function oneWay(myVal) { var deferred = Q.defer(); if (myVal < 0) ...

The issue lies with Express Mongoose failing to store the data

Encountering some issues when trying to save an object created in Express nodejs using mongoose. Despite receiving a confirmation that the object is saved, it cannot be located even after attempting to access it through the server. Express route for savi ...

Exploring the integration of external javascript AMD Modules within Angular2 CLI

During my experience with Angular2 pre-releases, I found myself using systemjs to incorporate external JavaScript libraries like the ESRI ArcGIS JavaScript API, which operates on AMD modules (although typings are available). Now that I am looking to trans ...

express.static() fails to serve files from public directories when accessed via router paths other than "/"

Express static configuration: app.use(express.static(__dirname + "/public")); Directory Structure: --public --assets --js --[JavaScript scripts] --stylesheets --[CSS files] Defined Routes: const shopRoutes = require('./routes/shopRo ...