Google Apps Script HTML Form

Google Apps Script HTML Form

HTML Email Form

html:

<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function submitForm(form) {
google.script.run
.withSuccessHandler(function(value){
document.getElementById('message').innerHTML = value;
document.getElementById('name').value = '';
document.getElementById('email').value = '';
document.getElementById('comment').value = '';
})
.submitData(form);
}
</script>
</head>
<body>
<h2>Feedback Form</h2>
<div id="message" style="color:green"></div>
<form>
<br /><input id="name" type="text" name="name" placeholder="Your Name">
<br /><input id="email" type="email" name="email" placeholder="Your Email">
<br /><textarea id="comment" rows="10" cols="40" name="comment"></textarea>
<br /><input type="button" value="Submit" onclick="submitForm(this.parentNode);" />
</form>
</body>
</html>

Google Script:

function submitData(form) {
var subject='New Feedback';
var body=Utilities.formatString('name: %s <br />Email: %s<br />Comment: %s', form.name,form.email,form.comment);
var to = 'my-email@email.com';
MailApp.sendEmail({to: to,subject: subject,htmlBody: body});
//Logger.log('name: %s <br />Email: %s<br />Comment: %s', form.name,form.email,form.comment);
return Utilities.formatString('name: %s <br />Email: %s<br />Comment: %s', form.name,form.email,form.comment);
}
//It works as a dialog
function showTheDialog() {
var userInterface=HtmlService.createHtmlOutputFromFile('aq7');
SpreadsheetApp.getUi().showModelessDialog(userInterface, "Emails")
}

Sample Image

Sample Image

I didn't actually test it with the mailapp line. I just used the Logger and saw that it returned the feedback message.

google apps script: html - form submit, get input values

Html form has a default behavior of navigating to the submission link. To prevent that default behavior you can use event.preventDefault() function in HTML like so:

 <form id="myForm" onsubmit="event.preventDefault(); google.script.run.processForm(this)">

Note: You can find more detailed explanation here

The form elements are sent as an object in the argument to the processForm function, to view them you can use JSON.stringfy(). Learn more about objects here

Your processForm function would be modified like so:

function processForm(formObject) {
var ui = SpreadsheetApp.getUi();
ui.alert(JSON.stringify(formObject))
// To access individual values, you would do the following
var firstName = formObject.firstname
//based on name ="firstname" in <input type="text" name="firstname">
// Similarly
var lastName = formObject.lastname
var gender = formObject.gender
ui.alert (firstName+";"+lastName+";"+gender)
}

HTML Form Submission to Google Sheets using Apps Scripts Landing Thank You Page

I figured this out actually. I used the code on the original guide with a modification. In my HTML I removed the previous <script> section and changed it to the following:

<script>
window.addEventListener("load", function() {
const form = document.getElementById('googleform');
form.addEventListener("submit", function(e) {
e.preventDefault();
const data = new FormData(form);
const action = e.target.action;
fetch(action, {
method: 'POST',
body: data,
})
.then(() => {
window.location.href = 'URL of thank you page';
})
});
});
</script>

Prefill an HTML input with Google Apps Script variable

You can use Templated HTML for this. With scriptlets you can pass the variable to the HTML as documented here.

To do this you would need to put this into you .gs code:

var ui = SpreadsheetApp.getUi();
var email = Session.getEffectiveUser().getEmail();
var html = HtmlService.createTemplateFromFile('filename');
html.email = email;
var output = html.evaluate();
ui.showSidebar(output);

Then for your form you need to insert the scriptlet <?= email ?> as the value:

<form action="">
<div>
<label for="inputmail2">Mail</label>
<input type="email" id="inputmail2" value="<?= email ?>">
</div>
<div>
<label for="inputproblem">Your Problem</label>
<textarea id="" ></textarea>
</div>
<div>
<button type="submit">Enviar</button>
</div>
</form>

Google Apps Script HTML form won't submit for overseas user

Looks like I just needed to add this as a Webapp and that fixed the issue. Thank you for the suggestions!

//OPEN THE FORM IN SIDEBAR 
function showFormInSidebar() {
var form = HtmlService.createTemplateFromFile('test').evaluate().setTitle('New Client');
SpreadsheetApp.getUi().showSidebar(form);
}

function doGet() {
var form = HtmlService.createTemplateFromFile('Index').evaluate().setTitle('New Client');
form.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
return form;
}

test.html

<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<center>
<embed type="text/html" src="redacted" width="290" height="800">
</center>
</body>
</html>

How to make submission function work in a web form that is created using Google Apps Script and embedded in a Google Site?

Issue and workaround:

I think that in your situation, your goal is difficult to be directly achieved using your showing script. The reason for this has already been mentioned in Gustavo's comment.

When I saw your comment, it seems that you are required to run the Web Apps on the Google side.

In this case, I thought that a workaround might be required to be used. In this answer, in order to achieve your goal, I would like to propose a workaround. The point of this workaround is as follows.

  • In your script, the value of <select id="dropdownList" name="cake" class="form-control"></select> is sent to doPost using action="<?!= getScriptUrl(); ?>" method="post" of the form.
  • In this workaround, the value is sent to Google Apps Script using google.script.run. And, after the value was completely submitted, the HTML body is overwritten by result.html.

When this point is reflected in your script, it becomes as follows.

Modified script:

index.html

Please modify index.html as follows.

<!DOCTYPE html>
<html>
<head>
<base target="_top">
<!-- <?!= include("css"); ?> -->
</head>
<body id="body" onload="addOptions()">
<form id="form">
<div>
<h1 id="Question">
Choose either cheesecake or chocolate cake.
</h1>
<select id="dropdownList" name="cake" class="form-control">
</select>
</div>
<p>
<div style="width:100px;height:500px;border:1px solid #000;">
Blank box to scroll down
</div>
</p>
<p>
Please do not forget what you've answered in the <a href="#Question" target="_self">question<a>
</p>
<div class="form-submit">
<input type="submit" name="" value="Submit" onclick="sample(this);return false;">
</div>
</form>
</body>
<?!= include('JavaScript') ?>
</html>

JavaScript.html

Please add the following function to JavaScript.html.

function sample(e) {
const f = document.getElementById("form");
const obj = { parameters: [...f].reduce((o, g) => (o[g.name] = [g.value], o), {}) };
google.script.run
.withSuccessHandler((res) => {
document.getElementById("body").innerHTML = res;
})
.sample(obj);
}
  • In this sample script, in order to directly use your doPost, the value of obj is prepared. Please be careful about this.

Code.gs: Google Apps Script side

Please add the following function to Code.gs. This function use your doPost.

function sample(e) {
return doPost(e).getContent();
}

Testing:

When this modification is reflected in your script and your Web Apps is embedded to a Google site, when the submit button is clicked, the value of cake is sent to the Google Apps Script side and result.html is displayed. I thought that this situation might be your expected result.

Note:

  • This modification is a simple modification for explaining the workaround. So, please modify this for your actual situation.

  • When you modified the Google Apps Script, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful this.

  • You can see the detail of this in the report of "Redeploying Web Apps without Changing URL of Web Apps for new IDE".

  • About the internal link of the Web Apps on Google site, it seems that when the while page of Web Apps is embedded and the scrollbar is not shown, the internal link doesn't work. When the scrollbar of the frame is shown, the link works. In this case, it seems that the internal link cannot be worked using both HTML and Javascript. And, I cannot confirm the error message.

Apps Script: Get user input from HTML form and save them as global variables

You can use Properties Service of Apps Script.

This service allows scripts to store strings as key-value pairs scoped
to one script, one user of a script, or one document in which an
editor add-on is used.

In your case, there are 2 options you can choose. Script Properties and User Properties.

The difference between the two is the content of Script Properties are shared to all users while User Properties is only available to the current user of a script, add-on, or web app.

Here I created an example of how to use Properties.

function setProperties(lastName = "Test Last Name", email = "Test Email", phone = "Test Phone"){
var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperties({'lastName': lastName, 'email': email, 'phone':phone})
}

function readProperties(){
var scriptProperties = PropertiesService.getScriptProperties();
Logger.log(scriptProperties.getProperties());
}

Here I run the readProperties() function first and the result is

Sample Image

Then I run the 'setProperties()' and rerun the readProperties() function again:

Sample Image

I reload the script page and ran the readProperties() function:

Sample Image

To add it in your script, you can set the properties in AddUserInputToSheet() and call it anywhere in your script.

Example:

function AddUserInputToSheet(gender, firstName, lastName, age, email, phone) {
var url = 'SHEET_URL';
var ss = SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("SHEET_NAME");
webAppSheet.appendRow([gender, firstName, lastName, age, email, phone]);

var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperties({'lastName': lastName, 'email': email, 'phone':phone})
}

function someFunction(){
var scriptProperties = PropertiesService.getScriptProperties();
var data = scriptProperties.getProperties();
var lastName = data["lastName"];
var email = data["email"];
var phone = data["phone"];
//some operations here
}


Related Topics



Leave a reply



Submit