I want to have 3 text fields with labels and a button on sidebar, clicking the button should send content of text fields to spreadsheet script function for further processing. I know how to create and display the sidebar, also how to trigger script function with button click but have no idea how to send text fields content.
// SidePanel.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<button onclick='f1()'>Update the address</button>
<script>
function f1() {
google.script.run.getAddress();
}
</script>
</body>
</html>
// display sidebar in gs
function showSidebar(){
var html = HtmlService.createHtmlOutputFromFile('SidePanel').setTitle('Helper').setWidth(100);
SpreadsheetApp.getUi().showSidebar(html);
}
Here is an example that will help you understand how to send values from the sidebar to the google sheet
Html Code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<button onclick='f1()'>Update the address</button>
<!-- Create a input field to except a value form user, in this case there name -->
Your Name:
<input type="text" id="name"><br>
<!-- Create a button to send the value to the spreadsheet -->
<button onclick='sendName()'>Send Name</button>
<script>
function f1() {
google.script.run.getAddress();
}
function sendName(){
//Get the value of the input field
var name = document.getElementById("name").value
//Log the value of input field in the web browser console (usually used for debugging)
console.log(name)
//Send the value of the text field as a arugment to the server side function.
google.script.run.enterName(name)
}
</script>
</body>
</html>
The HTML code above use the input field to get values from the user. You can access the value of the input field using DOM methods. The value of the text field is stored in the var name
in function sendNames()
. This is passed to the google script function as an argument google.script.run.enterName(name)
.
Your google script (aka server-side code)
function showSidebar(){
var html = HtmlService.createHtmlOutputFromFile('SO_sideBar_Example').setTitle('Helper').setWidth(100);
SpreadsheetApp.getUi().showSidebar(html);
}
// Sets the value of A1 cell to value entered in the input field in the side bar!
function enterName(name){
var ss = SpreadsheetApp.getActive()
var sheet = ss.getActiveSheet()
sheet.getRange("A1").setValue(name)
}
In the above server side code,function enterName()
receives the user input in the argument name
, which is entered in cell A1.
It is good practice to use withSuccessHandler() and withFailureHandler() as detailed here. To handle the success or failure of the server side code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With