1

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.

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much man.. I know it had to be something small that I was missing.
0

Try putting addEvent into window.onload

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.