I am trying to load options into a select box from a Google Sheet. My code currently almost works, however, the initial select option is not loading the corresponding value into the text input box when the page first displays. When the select box option is changed, the value is properly loaded into the text box. How can I load both the option and value on the initial page load?
Code.gs
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu("Sidebar")
.addItem("Show sidebar", "showSidebar")
.addToUi();
}
function showSidebar() {
var htmlWidget = HtmlService.createHtmlOutputFromFile('Test')
SpreadsheetApp.getUi().showSidebar(htmlWidget);
}
function getList() {
var items = SpreadsheetApp.getActive().getRange("Sheet1!A1:B3").getValues();
return items;
}
Test.html
<!DOCTYPE html>
<html>
<script>
function loadSelectBox() {
google.script.run.withSuccessHandler(function(ar)
{
var itemList = document.getElementById("itemSelectBox");
ar.forEach(function(item, index)
{
var option = document.createElement("option");
option.value = item[1];
option.text = item[0];
itemList.appendChild(option);
});
}).getList();
getPath();
}
function getPath()
{
var path = document.getElementById("itemSelectBox").value;
document.getElementById("itemPath").value = path;
}
</script>
<head>
<base target="_top">
</head>
<body>
<select id="itemSelectBox" onchange="getPath()" style="width: 60%"></select>
<br>
<input type="text" id="itemPath" style="width: 60%">
<script>
loadSelectBox();
</script>
</body>
</html>
In your script, how about the following modification?
Please modify loadSelectBox()
as follows.
function loadSelectBox() {
google.script.run.withSuccessHandler(function (ar) {
var itemList = document.getElementById("itemSelectBox");
ar.forEach(function (item, index) {
var option = document.createElement("option");
option.value = item[1];
option.text = item[0];
itemList.appendChild(option);
});
getPath(); // <--- Modified
}).getList();
}
getPath();
is put outside of google.script.run
. google.script.run
is run with the asynchronous process. By this, before withSuccessHandler
is run, getPath()
is run. I thought that this is the reason for your issue.