user4061059
user4061059

Reputation:

How can I process a form using Google Apps Script?

I am a total noob when it comes to GAS, but I want to pass a form to a local JS function (to validate the data), which then calls a Google function (to add it to a spreadsheet). Problem is: I can't even get the values out of the form!

My code is like this at the moment:

index.html:

<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">

<div>
  <form id="register" action="javascsript:void(0)" onsubmit="validateForm(this)">
    Email: <input type="text" name="email" placeholder="someone@example.com" /><br/>
    <p id="emailtext"></p><br/>
    Smartschool URL: <input type="text" name="url" /><br/>
    <p id="urltext"></p><br/>
    <input type="submit" value="Submit" />
  </form>
</div>

<?!= include('Javascript'); ?>

Javascript.html:

<script>
  function validateForm(form) {
      // THIS IS NEVER POPPING UP
      alert(form.email);
      return false;
  }
</script>

GoogleCode.gs:

function doGet(e) {
  return HtmlService.createTemplateFromFile('Page').evaluate();
}

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
      .getContent();
}

Upvotes: 1

Views: 2213

Answers (1)

Alan Wells
Alan Wells

Reputation: 31320

I added a console.log statement to the JavaScript, and looked at the log in my Google Chrome browsers console, and it shows that a form object is getting passed.

I added this line:

console.log('form: ' + form);

To your Javascript file:

<script>
  function validateForm(form) {
    console.log('form: ' + form);
      // THIS IS NEVER POPPING UP
      alert(form.email);
      return false;
  }
</script>

The browser console prints:

form: [domado object HTMLFormElement FORM]

So, the form object is getting passed. You can enumerate all the properties in the Form object to see what is in there, and available to retrieve.

for (var thePropurtees in form) {
  console.log('thePropurtees: ' + thePropurtees);
};

You'll get a real long list of everything in the Form object, and you'll notice that email is not in the list. What is in the list is an elements property, that turns out to be another object inside the form object. There is an elements object inside of the form object.

If I enumerate the form elements:

for (var thePropurtees in form.elements) {
  console.log('thePropurtees: ' + thePropurtees);
};

I get this:

thePropurtees: 0
thePropurtees: 1
thePropurtees: 2
thePropurtees: item
thePropurtees: email
thePropurtees: url
thePropurtees: namedItem

So, your email data must be in a sub object.

I was able to get the value out of the email input field with this:

console.log('the email value: ' + form.elements.email.value);

There are three levels of objects you need to access, before you can get at the values.

1) Form object
2) Elements object
3) Input object (email)

Your alert would need to be like this:

alert(form.elements.email.value);

Upvotes: 2

Related Questions