Transmitting a row of an HTML table back to Google Sheets

Is there a way to create buttons for each row in a table that, when clicked, send the entire row back to another sheet along with a timestamp? I am currently generating the table from an array but facing issues accessing the elements within it. Both the .getElementbyId() and .getElementbyId().appendChild methods are unable to access the button values. While I am able to save other form elements to my Google Sheet, I struggle with saving entire rows. Could someone suggest a better approach? Additionally, I am not sure how to implement this functionality for multiple buttons...

Javascript

function generateScheduleTable(dataArray){
    var tbody = document.getElementById("table-body-schedule");
    tbody.innerHTML="";

    dataArray.forEach(function(r, i){
      
      var row = document.createElement("tr");
      var col1 = document.createElement("td");
      col1.textContent = r[0];
      var col2 = document.createElement("td");
      col2.textContent = r[1];
      var col3 = document.createElement("td");
      col3.textContent = r[2];
      var col4 = document.createElement("td");
      col4.textContent = r[3];
      var col5 = document.createElement("td");
      col5.textContent = r[4];
      var col6 = document.createElement("td");
      col6.textContent = r[5];
      var col7 = document.createElement("button");
      col7.className = "btn";
      col7.id = "passbtn" +i;
      col7.innerHTML = "PASS";
      
      row.appendChild(col1);
      row.appendChild(col2);
      row.appendChild(col3);
      row.appendChild(col4);
      row.appendChild(col5);
      row.appendChild(col6);
      row.appendChild(col7);
      tbody.appendChild(row);
      col7.value = r;
      console.log(col7);
    });

    document.querySelectorAll('.btn').forEach(item => {
    item.addEventListener('click', event => {
    handleFormSubmit(passbtn0);
        })
    });

  }

function preventFormSubmit() {
var forms = document.querySelectorAll('form');    
document.getElementById('datestamp').value = document.getElementById('ct5').innerHTML;
document.getElementById('student_id').addEventListener("input",getStudentInfo); 
document.getElementById('event_id').addEventListener("select",DropDowns); 

 for (var i = 0; i < forms.length; i++) {
  forms[i].addEventListener('submit', function(event) {
  event.preventDefault();
  });
}

function handleFormSubmit(formObject) {
   document.getElementById('datestamp').value = document.getElementById('ct5').innerHTML;
   document.getElementById('student_id').select();
   document.getElementById('passbtn0').innerHTML;
   google.script.run.processForm(formObject);
}

HTML

<form id="myForm" onsubmit="handleFormSubmit(this)">
      <h3 class="text">Test App</h3>
      
      <div class = "submissions" id="event_id">
        <label for="event_id">Event Type</label>
           <select type="text" class="submissions" id="event_id" name="event_id">
         <option value = "" disabled selected>Select Event</option>
          <? for (var i=0; i<list.length;i++){ ?>
        <option><?= list[i]; ?></option>
      <? } ?>
           </select>               
    </div>

    <div class="form-group">

      <label for="room">Scan Location</label>
      <input class="submissions" type="text" id="room" name="room" placeholder="Scan Location">
    </div>

    <div class="form-group">
      <label for="student_id">Student ID</label>
      <input class="submissions" type="text" id="student_id" name="student_id" placeholder="Student ID" autofocus required>
    </div>

    <div class="form-group">
      <label class ="active" for="student_info">Student Information</label>
      <input disabled class="submissions" type="text" class="flow-text" id="student_info" name="student_info" placeholder="Student Information">

          <div class="row col s12" id="buttons">
          <br>
          <h5 class="text">Student Schedule</h5>
                <table class="striped">
                <thead>
                  <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Class</th>
                    <th>Period</th>
                    <th>Teacher</th>
                    <th>Room</th>
                    <th>Issue Pass</th>
                    <th>Hall Sweep Time</th>
                  </tr>
                </thead>
                <tbody id="table-body-schedule">
                
                </tbody>
                </table>
          </div>  
    </div>

  <div class="form-group">
        <input class="form-control form-control-lg" type='hidden' class="form-control" value='12356' name='datestamp' id='datestamp'>
        <br>
        <span id='ct5' class="flow-text text-warning" type="text" value=""></span>
   </div>

</form>

Code.gs

function processForm(formObject){ 

  var sheet = ss.getSheetByName('Log');
  sheet.appendRow([formObject.datestamp,
                formObject.student_id,
                formObject.passbtn0,
                formObject.room
                //formObject.email
                ]);
}

Answer №1

What do you think of this approach?

There's no need to deal with an html dialog for this task.

function insertSingleRow() {//choose a single row by selecting a cell within that row
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet0');
  const dsh = ss.getSheetByName('Sheet1');
  const data = sh.getRange(sh.getActiveRange().getRow(),1,1,sh.getLastColumn()).getValues().flat();
  dsh.appendRow(data);
}

or

function insertAllRows() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet0');
  const dsh = ss.getSheetByName('Sheet1');
  const data = sh.getActiveRange().getValues();
  data.forEach(row => dsh.appendRow(row));
}

or

function insertAll() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet0');
  const dsh = ss.getSheetByName('Sheet1');
  const data = sh.getActiveRange().getValues();
  dsh.getRange(dsh.getLastRow()+1,1,data.length,data[0].length).setValues(data);
}

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

Guide on adding HTML to an array every third time for displaying

Is there a way to generate div elements every 3 times in a for loop without outputting them as HTML? Any suggestions on how to achieve this? render() { const squareItems = []; for (var i=0; i < 9; i++) { if ((i % 3) == 0){ ...

Angular 2: Navigating through submenu items

I have a question about how to route submenu elements in Angular 2. The structure of my project is as follows: -app ---login ---registration ---mainApp (this is the main part of the app, with a static menu and links) -----subMenu1 (link to some con ...

I am having difficulty with my JavaScript code not being able to interpret the JSON output from my PHP code. Can anyone help me troubleshoot

Having trouble working with an AJAX call and handling the JSON object it generates in JavaScript? Here's a sample snippet of PHP code returning the JSON object: echo json_encode(array("results" => array(array("user" => $member['user'] ...

Using jQuery to show text upon hover using a `for` loop

I'm currently working on a webpage and incorporating a feature where hovering over specific div elements triggers the display of certain text in another div. There are 5 elements that I want to make hoverable and show text upon interaction. After imp ...

Flowing Waterways and Transmission Control Protocol

I have a unique piece of code that I recently discovered. After running it, I can connect to it using a Telnet client. const network = require('networking'); //creating the server const server = network.createServer(function (connection) { ...

Ways to make a component gradually appear and disappear in an Angular application

I have developed a task management application using Angular and I wanted to implement a fading effect for each task when it is created and before it is deleted. Despite successfully applying the fade in effect at the todo-item component level, I encounter ...

Adjust the size of the iframe image to fit seamlessly within the design

Is there a way to adjust the size of the image on the right without altering the layout design? The current GIF is 500x500px, but it is only displaying as 100x100px. Any assistance would be greatly appreciated! To see what I currently have (Demo with code ...

Refresh the JavaScript graph with new data from the AJAX request

Seeking assistance in updating my javascript chart data using ajax data retrieved from a database. The specific chart being referenced is an apex chart. After submitting a form via ajax, the returned result is as follows: type: "POST",crossDomain ...

Choosing between vm. and this. in Vue.js

My understanding of when to use the "this" keyword in vue.js is a bit cloudy. In the example below, whenever I replace "this" with "vm", the code stops functioning. I have come across instances where "self" was used instead of "this", but as someone who i ...

Setting a variable label to Key and assigning it the corresponding Value from a multidimensional array imported from a JSON file

I've been grappling with this issue for a few hours now, scouring stackoverflow and experimenting with different approaches to no avail. Any guidance would be greatly appreciated! Here's the structure of the JSON object I'm working with: [ ...

Formatting decimals with dots in Angular using the decimal pipe

When using the Angular(4) decimal pipe, I noticed that dots are shown with numbers that have more than 4 digits. However, when the number has exactly 4 digits, the dot is not displayed. For example: <td>USD {{amount| number: '1.2-2'}} < ...

What is the best way to tally the frequency of words in a collection of URLs using JavaScript?

I have a JSON object in WordPress that contains a list of URLs. I would like to determine the frequency of occurrence of the second part of each URL. Currently, the code snippet below is able to extract the remaining part of the URL after the prefix https ...

I seem to be struggling with hiding/showing a div element. Can you figure

I am in the process of creating a gallery that will display a div with images when a button is clicked. The issue I am facing is that when I have two buttons, only the last images are clickable. It's a bit difficult to explain, but you can see it in ...

The header row in HTML tables sometimes vanishes unexpectedly after sorting the table

Upon filtering the table, I noticed that the header disappears sporadically. The issue is that the table header row should remain in place regardless of whether or not the characters used for filtering are present in the table rows. In Example 1: When fil ...

Turn off Node.js Caching for Good

My Node.js website seems to be stuck using a cached version even after updating the code and using the -w option. I need to figure out how to disable caching with Forever in Node.js and completely uninstall it. I found this answer that confirms it caches: ...

What is the best method for purging a previously stored variable from the cache when making an Ajax call and simultaneously passing a

I am encountering an issue with variable loading during the ajax call. Upon clicking, I pass a variable to the ajax call which then sends the value to a PHP script. The data obtained is from: rnc.csv DLRNC01 DLRNC02 DLRNC03 DLRNC04 DLRNC05 DLRNC06 DLR ...

Determine the camera's new location following a rotation around a specific point on the mesh

I'm currently working on implementing the following scenario: When the user clicks on a mesh, focus the perspective camera on that point Allow the user to rotate the camera using orbitControls After rotation, adjust the camera position and target so ...

Attempting to replicate the functionality of double buffering using JavaScript

In my HTML project, I have a complex element that resembles a calendar, with numerous nested divs. I need to refresh this view in the background whenever there are updates on the server. To achieve this, I set up an EventSource to check for data changes on ...

Explore an object to locate an element along with its parent

Here is an example of an object: $scope.categories = [ { value: 'One', id: 1, childs: [ { value: 'Two', id : 2, childs: [ { v ...

Managing sessions with PHP and Angular.js involves retrieving and storing session data to maintain user

Seeking assistance on setting up a help session store using PHP and Angular.js for my login app. Upon successful login, the user's session should be stored and the session data retrieved upon redirection to the next page. Below is an outline of my cod ...