0

I'm using Google App Script to create an HMTL page where the user can enter a receipt number to do a lookup through a backend function generateInvoice. That function returns the receipt information and displays it on the front end with the "Email Invoice" button. Once the user clicks on the button, I attempt to collect what's being displayed through document.getElementById ('name').value but the result is "undefined".

Can I somehow pass the invoiceData variable from the searchReceipt to the sendEmail function? I know google.script.run.withSuccessHandler returns a void so I don't think it's possible but worth asking. If it can't be done, how can I obtain the value from the Element ID?

<html>
  <head>
    <base target="_top">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <!--Import Google Icon Font-->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <!-- <?!= include ("css") ?> -->
    <style>
      .error {
        padding-top: 20px;
        color: red;
      }

      .info {
        font-weight: 600;
      }

      th {
        color: #1976d2;
      }

      td {
        height: 50px;
      }
    </style>
  </head>
  <body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <div class="container">
      <div class="row">
        <div class="col s12">
          <img class="responsive-img" style="max-width: 300px" src="https://oasislaundry.net/wp-content/uploads/2020/11/cropped-oasislaundry_logo-e1605832264548.png">
        </div>
      </div>
      <div class="row">
        <div class="col s12">
          <h3 class="grey-text">Customer Invoice</h3>
        </div>
      </div>
      <div class="row" style="padding: 25px 25px">
          <div class="input-field col">
            <input id="receiptNumber" type="text" class="validate">
            <label for="receiptNumber">Receipt Number</label>
            <span class="helper-text">Must be 5 digits or more.</span>
          </div>
          <div class="col" style="padding-top: 20px">
            <button id="searchBtn" class="waves-effect waves-light btn-small blue lighten-1" onclick="searchReceipt()"><i class="material-icons left">search</i>search</button>
          </div>
      </div>
      <div class="row">
        <div class="col divider s8"></div>
      </div>
      <div class="row">
        <div id="error" class="error"></div>
      </div>
      <div id="invoiceData" class="row"></div> <!-- Column div is defined in the script section -->
      <div class="row">
        <div class="col s12" id="emailStatus"></div>
      </div>
    </div> <!-- CONTAINER -->
    
    <script>
      // Simulate button click when the Enter key is pressed
      document.getElementById ('receiptNumber').addEventListener ('keypress', 
        function (event) {
          if (event.key === 'Enter') {
            event.preventDefault ();
            document.getElementById ('searchBtn').click ();
          }
        }
      );

      // Function executed from the search button
      function searchReceipt () {
        const receiptNumber = document.getElementById ('receiptNumber').value;
        
        // Reset all values prior to executing each search
        document.getElementById ("receiptNumber").value = '';
        document.getElementById ('error').innerHTML = '';
        document.getElementById ('invoiceData').innerHTML = '';
        M.updateTextFields ();

        google.script.run.withSuccessHandler (
          function (invoiceData) {
            if (invoiceData == 'FAILED') {
              document.getElementById ('error').innerHTML = 'ERROR: No invoice found. Check the invoice number and try again.';
            }
            else {
              console.log ('Receipt Data: ', invoiceData);

              // Customer Information
              let displayInvoice = '<div class="row"><div class="col s4 m2 info" style="padding-bottom: 20px"><h5 class="red-text text-darken-2">Receipt</h5></div>';
              displayInvoice += `<div class="col s8 m10" style="padding-bottom: 20px"><h5 id="invoice_number" class="red-text text-darken-2">${invoiceData ['receipt']}</h5></div></div>`;
              displayInvoice += '<div class="row"><div class="col s4 m2 info">Customer Name:</div>';
              displayInvoice += `<div id="name" class="col s8 m10">${invoiceData ['fullName']}</div>`;
              displayInvoice += '<div class="col s4 m2 info">Address:</div>';
              displayInvoice += `<div id="address1" class="col s8 m10">${invoiceData ['address_1']}</div>`;
              displayInvoice += '<div class="col s4 m2 info">City, State, Zip:</div>';
              displayInvoice += `<div id="address2" class="col s8 m10">${invoiceData ['address_2']}</div>`;
              displayInvoice += '<div class="col s4 m2 info">Phone Number:</div>';
              displayInvoice += `<div id="phone" class="col s8 m10">${invoiceData ['phone']}</div>`;
              displayInvoice += '<div class="col s4 m2 info">Email Address:</div>';
              displayInvoice += `<div id="email" class="col s8 m10">${invoiceData ['email']}</div></div>`;
              
              // Receipt Table
              displayInvoice += '<div class="row"><div class="col s12" style="padding-top: 50px">';
              displayInvoice += '<table class="striped">';
              displayInvoice += '<thead>';
              displayInvoice += '<tr>';
              displayInvoice += '<th>Description</th>';
              displayInvoice += '<th>Qty</th>';
              displayInvoice += '<th>Unit Price</th>';
              displayInvoice += '<th>Total Price</th>';
              displayInvoice += '</tr>';
              displayInvoice += '</thead>';
              displayInvoice += '<tbody>';

              const cartLength = invoiceData ['cartItems'].length;
              for (let i = 0; i < cartLength; i++) {
                displayInvoice += `<tr><td>${invoiceData ['cartItems'][i]['description']}</td>`;
                displayInvoice += `<td>${invoiceData ['cartItems'][i]['quantity']}</td>`;

                if (invoiceData ['cartItems'][i]['unitPrice'] > 0 || invoiceData ['cartItems'][i]['unitPrice'] > 0) {
                  displayInvoice += `<td>$${invoiceData ['cartItems'][i]['unitPrice']}</td>`;
                  displayInvoice += `<td>$${invoiceData ['cartItems'][i]['totalPrice']}</td></tr>`;
                } else {
                  displayInvoice += `<td>-$${Math.abs (invoiceData ['cartItems'][i]['unitPrice']).toFixed (2)}</td>`;
                  displayInvoice += `<td>-$${Math.abs (invoiceData ['cartItems'][i]['totalPrice']).toFixed (2)}</td></tr>`;
                }
              }
              
              // Filling in empty table to make the table looks full
              for (let i = 0; i < 2; i++) {
                displayInvoice += '<tr><td></td>';
                displayInvoice += '<td></td>';
                displayInvoice += '<td></td>';
                displayInvoice += '<td></td></tr>';
              }

              // Make border solid
              displayInvoice += '<tr style="border-bottom: 1px solid; border-color: #1976d2">';
              displayInvoice += '<td colspan="100%"></td></tr>';
              displayInvoice += '<tr><td></td><td></td>';
              displayInvoice += '<td class="info">Subtotal</td>';
              displayInvoice += `<td><div id="subtotal">$${invoiceData ['subtotal']}</div></td></tr>`;

              displayInvoice += '<tr><td></td><td></td>';
              displayInvoice += '<td class="info">Tax</td>';
              displayInvoice += `<td><div id="tax">$${invoiceData ['tax']}</div></td></tr>`;

              displayInvoice += '<tr><td></td><td></td>';
              displayInvoice += '<td class="info">Payment / Credit</td>';
                            
              if (invoiceData ['payment'] == 0) {
                displayInvoice += `<td><div id="payment">$${invoiceData ['payment']}</div></td></tr>`;
              } else {
                displayInvoice += `<td><div id="payment">-$${invoiceData ['payment']}</div></td></tr>`;
              }

              displayInvoice += '<tr><td></td><td></td>';
              displayInvoice += '<td class="info">Total</td>';
              displayInvoice += `<td><div id="total">$${invoiceData ['total']}</div></td></tr>`;

              displayInvoice += '</tbody>';
              displayInvoice += '</table>';
              displayInvoice += '</div></div>';

              // Payment Link
              displayInvoice += '<div class="row"><div id="paymentLink" class="col s12 right-align" style="padding-bottom: 10px">';
              displayInvoice += `<a href="${invoiceData ['paymentLink']}" target="_blank">Payment Link</a></div></div>`;
              
              // Email Invoice Button
              displayInvoice += '<div class="row"><div class="col s12 center-align">';
              displayInvoice += '<button id="searchBtn" class="waves-effect waves-light btn-small blue lighten-1" onclick="sendEmail()"><i class="material-icons left">email</i>EMAIL INVOICE</button></div></div>';

              document.getElementById ('invoiceData').innerHTML = displayInvoice;
            }
          }
        ).generateInvoice (receiptNumber);  // The receiptNumber is sent to backend script to process and then returns it through invoiceData
      }

      // Function executed from the Email Invoice button
      function sendEmail () {
        let i = 0;
        let items = {};
        let cartItems = [];

        let table = document.getElementsByTagName ('table')[0];
        let td = table.getElementsByTagName ('td');

        console.log ('Name: ', document.getElementById ('name').value);

        // document.getElementById ('emailStatus').innerHTML = td [1].innerText;

        // Take the table data and convert it to dictionary
        while (td [i].innerText != '') {
          if (i % 4 == 0) {
            items ['description'] = td [i].innerText;
            i++;
            continue
          }
          if (i % 4 == 1) {
            items ['quantity'] = td [i].innerText;
            i++;
            continue
          }
          if (i % 4 == 2) {
            items ['unitPrice'] = td [i].innerText;
            i++;
            continue
          }
          if (i % 4 == 3) {
            items ['totalPrice'] = td [i].innerText;
            cartItems.push (items);
            items = {};
            i++;
          }
        }

        console.log ('Cart Items: ', cartItems);
    }
    </script>
  </body>
</html>```
dreamzboy
  • 795
  • 15
  • 31
  • 2
    `document.getElementById ('name')` is a div, not an input. Only inputs have values. To get the contents of a div use `.textContent`. – Barmar Aug 26 '23 at 04:32

0 Answers0