I'm trying to create a dialog box using Google Apps Script that collects a user's name and then updates a specific cell in a Google Sheet with a greeting. The dialog box appears correctly, but when I click the submit button, I receive a useless error in the console. See screenshot below
Here's the code I'm using:
HTML (dialog.html):
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form id="myForm">
<label for="name">Enter Your Name:</label>
<input type="text" id="name">
<input type="button" value="Submit" onclick="collectData()">
</form>
<script>
function collectData() {
var name = document.getElementById('name').value;
google.script.run
.withSuccessHandler(closeDialog)
.withFailureHandler(function(error) { console.error('ERROR:', error); })
.updateSheet(name)
}
function closeDialog() {
google.script.host.close();
}
</script>
</body>
</html>
Google Apps Script:
function showDialog() {
var html = HtmlService.createHtmlOutputFromFile('dialog')
.setWidth(300)
.setHeight(200);
SpreadsheetApp.getUi().showModalDialog(html, 'Enter Your Name');
}
function updateSheet(name) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sheet.getRange('A1').setValue('Hello, ' + name + '!');
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Custom Menu')
.addItem('Show Dialog', 'showDialog')
.addToUi();
}
The modal window opens and looks fine, but the submit button results in this error that gives no useful information. I've checked the HTML content, permissions, and browser compatibility and manually executed the functions, but the issue persists. I've also tried logging something in the updateSheet()
function, but nothing gets logged.
Has anyone encountered this error before, or is something wrong with my code that I'm overlooking? I've checked tutorials on this feature of sheets, and it seems I'm doing everything right.
Update:
I tried using event.preventDefault()
in the form's onsubmit
handler to prevent the default form submission action, as suggested, also the "duplicate" questions had nothing to do with this, as they were related to the page refreshing which is not happening here. but just for giggles I tried adding onsubmit="return false"
to the form and just turning the button into purely an onclick
function, and that didnt work either:
<form id="myForm" onsubmit="collectData(event)">
<!-- ... -->
</form>
<script>
function collectData(event) {
event.preventDefault();
// ...
}
</script>
Unfortunately, this change did not resolve the issue, and I'm still encountering the same error.
Hopefully, someone with experience in this specific area or who has faced a similar issue can provide insight into what might be going wrong.