MOO
MOO

Reputation: 193

How to get data from html form using Google App Script

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>

enter image description here

Upvotes: 0

Views: 2548

Answers (2)

Trashman
Trashman

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

Umair Mohammad
Umair Mohammad

Reputation: 4635

Two things :

  1. 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()]

  2. We have to use field name and not id [currently you are using id, cross check it, see capitalization]

So you have two options :

  1. Change name of fields to match that in script

<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

  1. Change name used in script to match that in form

use form.firstName and form.lastName in script in code.gs [instead of form.firstname and form.lastname]

Upvotes: 1

Related Questions