Search code examples
javascripthtmlgoogle-apps-scripteventsweb-applications

How do I know which button was clicked in the Google Apps script?


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?


Solution

  • 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