Iris Wang
Iris Wang

Reputation: 21

Pass variable in Google Apps Scriptlet to javascript

I just started coding with HTML and scriptlets within Google Sheets.

Trying to pass the array variable teacherArrayLean from the scriptlet (enclosed by <? ... ?>) to the <script>. However, <script> doesn't read the variable; when I replace the variable with constants, the scripts runs no problem so I know it's not the rest of the code.

Does anyone know how to use the variable in <script>? Thank you!

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <style>
    table, td, th {border: 1px solid black;}
    table {border-collapse: collapse;}
    th {text-align: left;}
  </style>
  </head>
  <body>

    <? var querySheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('query');
       var teacherArrayRaw = querySheet
                   .getRange(2, 4, querySheet.getLastRow() - 1, 1)
                   .getValues();
       teacherArrayRaw.sort();
       var teacherArrayLean = [];
       teacherArrayLean.push(teacherArrayRaw[0]);
       for(var n in teacherArrayRaw) {
         if(teacherArrayLean[teacherArrayLean.length-1].toString().trim() != teacherArrayRaw[n].toString().trim()) {
           teacherArrayLean.push(teacherArrayRaw[n]);
         }
       } 
       ?>

    <table id="calendar"></table>

    <script>
    var teacherArrayLean = [];
        var table = document.getElementById("calendar");
        var row = table.insertRow(0);
        for (var col = 0; col < teacherArrayLean.length; col++) {
        var cell = row.insertCell(col);
        cell.innerHTML = teacherArrayLean[col];

      }
    </script>
  </body>
</html>

Upvotes: 2

Views: 839

Answers (1)

Titus
Titus

Reputation: 22474

You can do something like this:

<script>
    var teacherArrayLean = JSON.parse("<?=JSON.stringify(teacherArrayRaw)?>");
    ....
</script>

Upvotes: 4

Related Questions