I am using modal dialog to select a range from here Prompt user for range in .gs function, pass array to html script and re-focus on the HTML dialog
There are two events in a modal dialog.
The first selects a range, and the second closes the dialog.
<input type="button" id="btn1" value="Range Selected" onClick="selectRange();" />
<br /><input type="button" id="btn2" value="close" onClick="clearAndClose();"; disabled="true" />
How do you combine these into one event so that when the range is selected, the dialog closes without clicking the close button?
Make the selectRange() a server side function:
gs:
function saveRange() {
PropertiesService.getScriptProperties().setProperty("range",SpreadsheetApp.getActiveRange().getA1Notation());
SpreadsheetApp.getActive().toast(PropertiesService.getScriptProperties().getProperty("range"));
}
function selectRangeDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile("ah2"),"Range Dialog")
}
html:
<!DOCTYPE html>
<html lang="en">
<head>
<base target="_top">
<title>My Html</title>
</head>
<body>
<h1>Please Select a Range and Press Save</h1>
<br><input type="button" value="Save" onClick="google.script.run.withSuccessHandler((v) => google.script.host.close()).saveRange();">
</body>
</html>
Here's another way to accomplish the same thing without requiring a separate html file.
function saveRange() {
const ss = SpreadsheetApp.getActive();
PropertiesService.getScriptProperties().setProperty("range", `${SpreadsheetApp.getActiveSheet().getName()}!${SpreadsheetApp.getActiveRange().getA1Notation()}`);
ss.toast(PropertiesService.getScriptProperties().getProperty("range"));
}
function launchSaveRangeDialog() {
const html = '<!DOCTYPE html> <html lang="en"> <head> <base target="_top"> <title>My Html</title> </head> <body> <h1>Please Select a Range and Press Save</h1> <br><input type="button" value="Save" onClick="google.script.run.withSuccessHandler((v) => google.script.host.close()).saveRange();"> </body> </html>';
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), "Save Dailog");
}