Home > Blockchain >  How to set a <div> tag text value from Google Apps Script with JavaScript?
How to set a <div> tag text value from Google Apps Script with JavaScript?

Time:10-16

How are the elements foo and bar set to the values for their corresponding variables?

html:

<!DOCTYPE html>
<html>

<head>
  <base target="_top">
  <script>
    function sendFoo()
    {
      var foo = document.getElementById("foo").value;
      google.script.run.setFoo(foo);
      var bar = google.script.run.getBar();
      document.getElementById("foo").value = '';
      document.getElementById("bar").childNodes[0].textContent = "put variable here..";
    }
  </script>
</head>

<body>
  foo is:<input type="text" id="foo" />
  <input type="button" value="sendFoo" onclick="sendFoo()" /> <br> <br> <br>


    bar is:  <div id="bar">Change only me<div>but not me</div>
</body>
</html>

code:

const SPREADSHEET_ID = "1L3Sd-J780mQtb7JYsmJzInI1kMdrQA8GbLspQJ5eVW4";
const SPREADSHEET_NAME = "data";

function setFoo(foo) {
  // Logger.log("setFoo..");
  // Logger.log(foo);
}

function getBar() {
  //  Logger.log("getBar..");
  return "baz";
}


function getUrl() {
  // Logger.log("getUrl..");

  var url = ScriptApp.getService().getUrl();
  return url;
}


function doGet(e) {
  // Logger.log("doGet..");
  var htmlOutput = HtmlService.createTemplateFromFile('FooBarBaz');
  htmlOutput.url = getUrl();
  return htmlOutput.evaluate();
}

Server side logs show foo and bar values when uncommented. However, there seems no output from console.log("some text"); from within the function defined on the HTML page.

CodePudding user response:

If you are trying to get the response of the google script function, then you will have to call that with success handler. google.script.run.getBar() should be updated as:

var bar = '';
google.script.run.withSuccessHandler((response)=>{
  bar = response;
  console.log(response); // prints 'baz' on console.
}).getBar();

You can use this value to assign to the div or perform some other operations.

CodePudding user response:

function sendFoo()
    {
      var foo = document.getElementById("foo").value;
      google.script.run.setFoo(foo);
      google.script.run
      .withSuccessHandler((s) => {
        document.getElementById("bar").innerHTML = s;
      })
      .getBar();
      document.getElementById("foo").value = '';
      document.getElementById("bar").childNodes[0].textContent = "put variable here..";
    }
  • Related