Francisco Cortes
Francisco Cortes

Reputation: 1226

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.

Upvotes: 1

Views: 1766

Answers (2)

TheMaster
TheMaster

Reputation: 50452

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>

Upvotes: 2

Cooper
Cooper

Reputation: 64062

Try putting addEvent into window.onload

Upvotes: 0

Related Questions