Your script is currently calling addItem with no parameters, as soon as the page loads:
<script>
google.script.run.addItem();
</script>
Instead, you need to call this function when the Submit button is clicked. While we use HTML forms in Google Apps Script, we can't use the normal submit action; instead, we set up an input button, and use a click handler to collect the form content and transfer it to the server function.
Your Submit button could be something like this:
<input type="button" value="Submit"
onclick="google.script.run
.withSuccessHandler(google.script.host.close)
.addItem(this.parentNode)" />
The success handler will be invoked when a response is return
ed from the runner, addItem()
. To just close the dialog, use google.script.host.close
. You could also have a failure handler; it would be invoked if the runner threw an exception.
(Note: you had itemAdd
in your gs
, but addItem
in your JavaScript - that would never have worked.)
Your openInputDialog()
function is odd; it has an unnecessary return
in it that would stop the dialog from showing up, probably left over from some debugging attempt.
When the runner function, itemAdd()
, gets called, it should be passed the content of the HTML form. Since the submit button is a part of that form, the fields of the form appear as properties of its parent node in the DOM; so the click handler passes this.parentNode
as a parameter to the runner.
On the server side, itemAdd()
receives the form
object, so we need a parameter to facilitate operations on it. The named form fields are then referenced like this:
sheet.appendRow([" ", form.category, form.item, form.manupub, form.details, form.quantity]);
Anyway, this works now:
addItem.gs
function openInputDialog() {
var html = HtmlService.createHtmlOutputFromFile('Index').setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Add Item');
}
function itemAdd(form) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
sheet.appendRow([" ", form.category, form.item, form.manupub, form.details, form.quantity]);
return true;
}
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<br>
<form>
Category:<br>
<input type="text" name="category">
<br>
Item:<br>
<input type="text" name="item">
<br>
Manufacturer or Publisher:<br>
<input type="text" name="manupub">
<br>
Details:<br>
<input type="text" name="details">
<br>
Quantity:<br>
<input type="text" name="quantity">
<br><br>
<input type="button" value="Submit"
onclick="google.script.run
.withSuccessHandler(google.script.host.close)
.itemAdd(this.parentNode)" />
</form>
</html>