我是 .gs 的新手,所以这应该不难。
我有一个 Google 电子表格,其中一列中包含值(假设 A 列)。 我使用 .gs 创建了一个自定义菜单,用户将在其中选择一个选项。
单击其中一个选项(新组件),会出现一个弹出窗口,其中包含一个下拉菜单,用户应从其中选择值。
自定义菜单.gs
function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('bq Library Menu')
.addItem('Add new component', 'newComponent')
.addSeparator()
.addSubMenu(ui.createMenu('Modify existing component')
.addItem('Remove component', 'removeComponent'))
.addToUi();
}
function newComponent() {
var html = HtmlService.createHtmlOutputFromFile('NewComponentForm')
.setWidth(400)
.setHeight(300);
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showModalDialog(html, 'New Component Form');
}
NewComponentForm.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h2>Clickable Dropdown</h2>
<p>Select manufacturer from the list</p>
<div class="dropdown">
<button onclick="loadManufacturers()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content"></div>
</div>
</body>
我希望下拉菜单显示电子表格 A 列中的所有元素。我尝试了多种选择,但没有获得所需的结果。
那么,我需要如何继续实现下拉列表填充过程?
最佳答案
- 您想要创建一个选择框并输入电子表格“A”列中的值。
- 选择选择框中的某个值后,您想要检索该值。
如果我的理解是正确的,那么这个修改怎么样?我认为针对您的情况有多种答案,因此请将此视为其中之一。
修改后的脚本流程如下。
- 打开一个对话框。
- 点击“下拉”按钮。
- 通过
google.script.run
,在 Google Apps 脚本端运行getValuesFromSpreadsheet()
函数。 - 在
getValuesFromSpreadsheet()
中,从电子表格中检索值并将其返回给 Javascript。 - 在
withSuccessHandler()
处,检索返回的值。使用这些值创建一个选择框。 - 当选择了选择框的值时,将运行
selected()
并检索所选值。
反射(reflect)上述流程后,修改后的脚本如下。
天然气:
请将以下 Google Apps 脚本添加到 CustomMenu.gs
。
function getValuesFromSpreadsheet() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
return sheet.getRange(1, 1, sheet.getLastRow(), 1).getValues(); // Retrieve values and send to Javascript
}
- 在此示例脚本中,从事件电子表格的“Sheet1”中检索值。这些值位于“A”列中。
- 如果您想从其他范围和工作表中检索,请修改此项。
HTML:
请将以下 JavaScript 添加到 NewComponentForm.html
中。
<script>
function loadManufacturers() {
google.script.run.withSuccessHandler(function(ar) {
let select = document.createElement("select");
select.id = "select1";
select.setAttribute("onchange", "selected()");
document.getElementById("myDropdown").appendChild(select);
ar.forEach(function(e, i) {
let option = document.createElement("option");
option.value = i;
option.text = e;
document.getElementById("select1").appendChild(option);
});
}).getValuesFromSpreadsheet();
};
function selected() {
const value = document.getElementById("select1").value;
console.log(value);
}
</script>
- 使用
google.script.run
从电子表格中检索值。 - 使用
withSuccessHandler
从 Google Apps 脚本检索值。 - 单击“下拉”按钮时,会创建一个选择框。
- 可以在控制台看到所选值。
注意:
- 这是一个简单的示例脚本。所以请根据您的情况进行修改。
引用文献:
如果我误解了你的问题,我很抱歉。
关于javascript - 从 Google 电子表格中的列填充 HTML 下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54217028/