我正在尝试使用带有表单的侧边栏来获取用户输入.该代码绑定到Google表格文件.
Code.gs:
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Custom Menu')
.addItem('Show sidebar', 'showSidebar')
.addToUi();
}
function showSidebar() {
var html = HtmlService.createHtmlOutputFromFile('Page')
.setTitle('My custom sidebar')
.setWidth(300);
SpreadsheetApp.getUi()
.showSidebar(html);
}
function processForm(formObject) {
var ui = SpreadsheetApp.getUi();
ui.alert("This should show the values submitted.");
}
page.html中:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
Please fill in the form below.<br><br>
<form id="myForm" onsubmit="google.script.run.processForm(this)">
First name:
<input type="text" name="firstname"><br><br>
Last name:
<input type="text" name="lastname"><br><br>
Gender:<br>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other<br>
<br>
<input type="submit" value="Submit">
</form><br>
<input type="button" value="Cancel" onclick="google.script.host.close()" />
</body>
</html>
当我按“提交”时,警报会打开并显示给定的消息,我的浏览器会打开一个显示空白页面的网址
(https://n-ms22tssp5ubsirhhfqrplmp6jt3yg2zmob5vdaq-0lu-script.googleusercontent.com/userCodeAppPanel?firstname=&lastname=&gender=male).
我希望警报显示提交的值,我不希望打开额外的页面.
非常简单的问题,但我读到的一切看起来都非常复杂.我只是想知道获取用户输入的最简单方法.
解决方法:
Html表单具有导航到提交链接的默认行为.要防止该默认行为,您可以在HTML中使用event.preventDefault()函数,如下所示:
<form id="myForm" onsubmit="event.preventDefault(); google.script.run.processForm(this)">
注意:您可以找到更详细的说明here
表单元素作为processForm函数的参数中的对象发送,以查看它们可以使用JSON.stringfy()
.了解有关对象的更多信息here
您的processForm函数将被修改如下:
function processForm(formObject) {
var ui = SpreadsheetApp.getUi();
ui.alert(JSON.stringify(formObject))
// To access individual values, you would do the following
var firstName = formObject.firstname
//based on name ="firstname" in <input type="text" name="firstname">
// Similarly
var lastName = formObject.lastname
var gender = formObject.gender
ui.alert (firstName+";"+lastName+";"+gender)
}