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?
CodePudding user response:
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
CodePudding user response:
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_—_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>