Search code examples
htmluser-interfacegoogle-apps-scriptgoogle-docs

Get textarea value from google document ui into gs code


I want to set the values of 2 variables in a gs code to be the text value in 2 text areas on the HTML file.

sidebar.html:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <input type="button" value="go go go!" onclick="google.script.run.mainFunction();"/> 
    <strong>Text Area 1</strong>
    <textarea id="textarea1" rows="2" cols="35">Text1</textarea>
    <strong>Text Area 2</strong>
    <textarea id="textarea2" rows="3" cols="35">Text2</textarea>
  </body>
</html>

code.gs:

mainFunction() {
  var textArea1Value = ???; // should be "Text1"/user's input
  var textArea2Value = ???; // should be "Text2"/user's input
  // some code
}

How do I achieve this? (what should I write instead of the "???" in the gs code?)

I've tried searching for a solution, but wasn't sure how to implement what I've found as the answers were too specific

Thanks


Solution

  • You need to pass the values as paramaters from the clientside to serverside

    For this, obtain the textareas by id within a Javascript code part and pass their values to google.script.run

    Sample modification o your code:

    sidebar.html:

        <input type="button" value="go go go!" onclick="myJSFunction()"/> 
        <strong>Text Area 1</strong>
        <textarea id="textarea1" rows="2" cols="35">Text1</textarea>
        <strong>Text Area 2</strong>
        <textarea id="textarea2" rows="3" cols="35">Text2</textarea>
        <script>
        function myJSFunction(){
          var text1 = document.getElementById("textarea1").value;
          var text2 = document.getElementById("textarea2").value;
          google.script.run.mainFunction(text1, text2);
        }
        </script>
    

    code.gs:

    function mainFunction(text1, text2) {
      var textArea1Value = text1; 
      var textArea2Value = text2;
      // some code
    }