在Google Sheet中使用getElementById返回null从ModalDialog中获取值.我能做什么?&



我试图从模态对话框中获得一个选择,以便在Google Sheets中粘贴选定的值,但我得到一个null

首先,我用googlessheets中的一个按钮执行ModalDialog,然后从下拉列表中选择一个选项。最后,我只得到一个空单元格。

我有以下。gs代码:

//Showing the ModalDialog in Sheets
var html = HtmlService.createHtmlOutputFromFile('Netsuite_menu')
.setWidth(300)
.setHeight(50);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showModalDialog(html, 'Select a pay method');
selection();

然后在一个单独的。gs文件

//Getting value from html selection
function selection(sel){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var mainSheet = ss.getSheetByName("selection_");
mainSheet.appendRow([sel,1]); //It just paste the '1'
}

这是netsuite_menu。html文件

<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<style>
.button {
background-color: indigo;
color: white;
padding: 2px;
border: none;
border-radius: 3px;
}
</style>
<script>
function runIt(){
var sel = document.getElementById("tipo").value;
google.script.run.selection(sel);
}
</script>
<body>
<form id="form">
<select id="tipo" name="selection" onchange="runIt()">
<option value="default" disabled selected>-- Select a pay method--</option>
<option value="driversA">Op. 1</option>
<option value="driversB">Op. 2</option>
<option value="business">Op. 3</option>
<option value="pay">Op. 3</option>
<option value="pex">Op. 4</option>
</select>
<button
id="btn"
class="button" 
value="Accept" 
name="LoginButton"
onclick="google.script.host.close();">
Accept
</button>
</form>
</body>
</html>

也许Chrome控制台显示的这个错误有助于理解具体的错误:输入图片描述

我相信你的目标如下。

  • 当接受按钮被点击时,您想要附加下拉列表中所选选项的值。

在这种情况下,下面的修改如何?

修改脚本:

在此修改中,您的HTML侧被修改。

<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<style>
.button {
background-color: indigo;
color: white;
padding: 2px;
border: none;
border-radius: 3px;
}
</style>
<script>
function runIt(){
var sel = document.getElementById("tipo").value;
console.log(sel)
google.script.run.withSuccessHandler(_ => google.script.host.close()).selection(sel);
}
</script>
<body>
<form id="form">
<select id="tipo" name="selection">
<option value="default" disabled selected>-- Select a pay method--</option>
<option value="driversA">Op. 1</option>
<option value="driversB">Op. 2</option>
<option value="business">Op. 3</option>
<option value="pay">Op. 3</option>
<option value="pex">Op. 4</option>
</select>
<button
id="btn"
class="button" 
value="Accept" 
name="LoginButton"
onclick="runIt()">
Accept
</button>
</form>
</body>
</html>
  • 如果您不想在点击接受按钮时关闭对话框,请将google.script.run.withSuccessHandler(_ => google.script.host.close()).selection(sel);修改为google.script.run.selection(sel);
  • 参考:

  • withSuccessHandler(函数)