简体   繁体   中英

button will not execute click function in google apps script html service

I've spent 2 days trying to figure this out so any help is appreciated.

I was following this nice little video tutorial series and I wanted to try something basic before getting any further: get an html button to show a javascript alert using google apps script and their HTML Service component, but for the life of me, I can't understand why the alert is not triggered.

Here's my code

Index.html

    <!DOCTYPE html>
        <html>
          <head>
              <script>
                 document.getElementById("btnSearch")
                         .addEventListener("click",showAlert);                
              function showAlert() {
                alert("hello world");
              }
              </script>
          </head>
          <body>
            <div>
              <label>Enter code</label>
              <input type="text" id="txtStudentID"/>
              <button id="btnSearch">Search</button>
            </div>
          </body>
        </html>

and my code.gs

function doGet() {
  return HtmlService.createHtmlOutputFromFile('Index');
}

I also try it like google shows it here : but I still don't get the alert to trigger after the button is pressed:

<input type="button" value="Search"
      onclick="google.script.run
          .withSuccessHandler(showAlert)
          .withUserObject(this)" />

it's like anything that starts with "document.getElementByID..." within the script tags will simply not work

What am I missing? is this something not longer supported with GAPS? is there a different/proper way to get this to work?

thank you in advance.

anything that starts with "document.getElementByID..." within the script tags will simply not work

Yes. Because at the time script tags are evaluated, there's no element with id btnSearch .

Solution(s):

  • Move the script to the bottom of DOM.
<div>
  <label>Enter code</label>
  <input type="text" id="txtStudentID" />
  <button id="btnSearch">Search</button>
</div>

<script>
  function showAlert() {
    alert('hello world');
  }
  document.getElementById('btnSearch').addEventListener('click', showAlert);
</script>
  • Alternatively, As the previous answer states, use the load trigger; so that the script is evaluated after the DOM is loaded.
<script>
  function showAlert() {
    alert('hello world');
  }
  function load1() {
    document.getElementById('btnSearch').addEventListener('click', showAlert);
  }
  window.addEventListener('load', load1);
</script>

尝试将addEvent放入window.onload

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM