1

When I have the following buttons in Google Apps Script html

<button id="movie" onclick="getMovie()">get Movie List</button>
<button id="music" onclick="getMusic()">get Music List</button>

How do I know which button is clicked in Google Apps Script? I tried using localStorage.getItem, but the gs file did not recognize localStorage. Can I import the value of the clicked button without using the event parameter?

Rubén
  • 34,714
  • 9
  • 70
  • 166
whytili
  • 107
  • 7
  • Does this answer your question? [Get ID of element clicked](https://stackoverflow.com/questions/28444457/get-id-of-element-clicked) – Kos Oct 06 '22 at 13:19
  • 2
    `without using the event parameter?` Why? – TheMaster Oct 06 '22 at 13:38
  • @TheMaster It was because I wanted to use the function I was trying to use without receiving the parameter. The problem has been resolved well. Thank you. – whytili Oct 11 '22 at 06:18
  • @Kos It's a little different, but the problem has been solved well. Thank you. – whytili Oct 11 '22 at 06:18

2 Answers2

1

You can make a generic function and then pass the object that the onclick function is associated with this.

Here is an example.

HTML_Test.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <button id="movie" onclick="buttonClick(this)">get Movie List</button>
    <button id="music" onclick="buttonClick(this)">get Music List</button>
    <script>
      function buttonClick(button) {
        alert("You clicked "+button.id);
        google.script.run.getButton(button.id);
      }
    </script>
  </body>
</html>

Code.gs

function getButton(id) {
  Logger.log("You pressed "+id);
}

Execution log

Oct 6, 2022, 7:17:00 AM Info    You pressed movie
TheWizEd
  • 7,517
  • 2
  • 11
  • 19
1

Whatever method that you use to get call a function on client-side, you might have to communicate with the server-side code using google.script.run, i.e. google.script.run.myFunction(id).

Since the event object is automatically generated, it doesn't make sense to avoid its use but it's possible by using this as the function parameter used as the value of the onclick attribute.

Note: Using onclick attribute, while it's still supported, it's is discouraged by the design principle "separation of concerns". See https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these for a specific explanation.

Here is client-side only sample of using this as explained above:

function getMovie(a){
  console.log(a.id)
}

function getMusic(b){
  console.log(b.id)
}
<button id="movie" onclick="getMovie(this)">get Movie List</button>
<button id="music" onclick="getMusic(this)">get Music List</button>

Related

Rubén
  • 34,714
  • 9
  • 70
  • 166