Reputation: 193
How I can pass/get data from the html form in Google apps script? I was trying many times but still can't get the right code. I hope someone can help me here with this problem.
Code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('Index');
}
function getValuesFromForm(form) {
var firstname = form.lastname,
lastname = form.firstname,
ss = SpreadsheetApp.openById('1XvrQFzVTlCqtB6HGggeGKraaLrd_8wdw6rAGVNVxYC0');
var sheet = ss.getSheets()[0];
sheet.appendRow([firstname, lastname]);
}
Index.html
<form>
First name: <input id="firstname" name="firstName" type="text" />
Last name: <input id="lastname" name="lastName" type="text" />
<input onclick="google.script.run.getValuesFromForm(this.form)" type="button" value="Add Row" />
</form>
Upvotes: 0
Views: 2548
Reputation: 1596
Another way is to change your form to use a "submit" type form and put the action in the main form field, as shown below:
<form action="javascript:void(0)" onsubmit="google.script.run.getValuesFromForm(this)">
First name: <input id="firstname" name="firstName" type="text" />
Last name: <input id="lastname" name="lastName" type="text" />
<input type="submit" value="Add Row" />
</form>
I believe the .gs code in your original question will work unmodified with this form.
Upvotes: 0
Reputation: 4635
Two things :
We have to pass parent , so that we can access it's children. this.form will send nothing[I guess] because this[input button] doesn't have form child. Rather you should send form[using parentNode or getElement()]
We have to use field name
and not id
[currently you are using id, cross check it, see capitalization]
So you have two options :
<form id='myForm'>
First name: <input id="firstname" name="firstname" type="text" /> Last name: <input id="lastname" name="lastname" type="text" />
<input onclick="google.script.run.getValuesFromForm(document.getElementById('myForm'))" type="button" value="Add Row" />
</form>
OR
use form.firstName
and form.lastName
in script in code.gs
[instead of form.firstname
and form.lastname
]
Upvotes: 1