Submit form results to google script? - html

I'm trying to submit the input results of an html form in a container-bound sidebar and copy them to a google sheet. I reviewed a few code examples from this site as well as others (https://www.packtpub.com/mapt/book/web_development/9781785882517/4/ch04lvl1sec48/submitting-form-using-google-script-api-method) but, perhaps because I'm a complete newbie at html/javascript/gas, found them confusing and difficult to follow such that the code I wrote isn't working and I can't figure out why.
In short, I'd like to pass the value entered in 'formcommenttext' input text box to my Google Apps Script function called 'postCommentToSheet', where I'm hoping I can get the value entered by the user and (eventually) write it to a google sheet.
Any suggestions?
Here's my html code:
<!-- input control to add comment -->
<form id="addCommentForm">
<fieldset>
<legend>Add your comment:</legend>
<br>
<input type="text" name="formcommenttext" value=""><br>
<input type="submit" value="Add" onclick="google.script.run.postCommentToSheet(this.parentNode);">
<input type="reset" value="Cancel">
</fieldset>
</form>
I have also include the following code snippet into the script portion of my html form (as suggested elsewhere) though i'm unclear what this does and how to edit it to fit my needs.
function postData(form){
google.script.run
.withSuccessHandler(callback)
.withFailureHandler(callback)
.postFormDataToSheet(form);
}
Here's my .gs code:
function postCommentToSheet(formObject) {
//read formcommenttext from add comment form:
//https://www.packtpub.com/mapt/book/web_development/9781785882517/4/ch04lvl1sec48/submitting-form-using-google-script-api-method
var result = GLOBAL_UI.alert(formObject.formcommenttext.value)
//get comments data sheet
var ss = GLOBAL_DataFile.getSheetByName("Comments");
ss.appendRow([formObject.formcommenttext]);
}

here is how it works :
<form id="addCommentForm">
<fieldset>
<legend>Add your comment:</legend>
<br>
<input type="text" name="formcommenttext" value=""><br>
<input type="submit" value="Add" onclick="google.script.run.postCommentToSheet(this.form);">
<input type="reset" value="Cancel">
</fieldset>
</form>
and the .gs part :
function sidebar(){
var sb = HtmlService
.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi().showSidebar(sb);
}
function postCommentToSheet(form){
Logger.log(JSON.stringify(form));
var ss = SpreadsheetApp.getActiveSheet();
ss.appendRow([form.formcommenttext]);
}
I added a log to check the content of the form answer and simplified a bit to make it functional in this small example.

You don't currently need the postData() function, but you could call it instead of google.script.run.postCommentToSheet() in case you wanted to do some processing before calling adding the comment to the sheet.
For example, you could run validations to prevent the user from, say, submitting a blank comment. I've included this exact functionality in my example as a demonstration.
Also included is a custom menu so that the sidebar can be opened from within the sheet and the CSS package for add-ons.
Index.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<!-- (OPTIONAL) Make your sidebar look consistent with Google Sheets with the below CSS https://developers.google.com/apps-script/add-ons/css -->
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<!-- input control to add comment -->
<form id="addCommentForm" onsubmit=checkData(this)>
<fieldset>
<legend>Add your comment:</legend>
<br>
<input type="text" name="formcommenttext" value="">
<br>
<input type="submit" value="Add">
<input type="reset" value="Cancel">
</fieldset>
</form>
<script>
function checkData(form) {
if (form.formcommenttext.value != "") {
google.script.run.postCommentToSheet(form);
}
}
</script>
</body>
</html>
Code.gs:
// Create a custom menu to open your sidebar
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [];
menuEntries.push({name: "Open Sidebar", functionName: "openSidebar"});
ss.addMenu("My Custom Menu", menuEntries);
}
// Open the sidebar
function openSidebar() {
var sidebar = HtmlService.createHtmlOutputFromFile("Index");
SpreadsheetApp.getUi().showSidebar(sidebar);
}
function postCommentToSheet(formObject) {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Comments"); // Almost ALWAYS better to explicitly define which sheet to write to
sheet.appendRow([formObject.formcommenttext]);
}

Related

Google Script HTML form submission

In google sheets I created a menu to add a new employee. It opens a modalDialog using html file (NewEmployee.html) that has a form inside collecting name, starting date, radio buttons (2) and salary (per hour).
HTML Code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function closeForm(){
google.script.host.close();};
function submitForm(){
google.script.run.getInfoFromSubmitForm(document.getElementById("employeeForm"));};
</script>
</head>
<style type="text/css">
.submit-button{
float: right;}
.cancel-button{
float: left;}
</style>
<body>
<div id="myForm">
<form id="employeeForm" class="form">
<label for="employeeName">Employee Name  </label>
<input
type="text"
id="employeeName"
name="employeeName"
employeeName="employeeName"
placeholder="This will also be the name of the Sheet"
style="width: 230px;"><br><br>
<label for="date">Please select start Date    </label>
<input type="date" id="date" name="date"><br><br>
<label for="employeeType">Please Select Employee Type</label><br>
<input type="radio" id="W2" name="employeeType" value="W2">
<label for="W2">W2</label><br>
<input type="radio" id="W9" name="employeeType" value="W9">
<label for="W9">W9</label><br><br>
<label for="salary">Please enter the Salary(per hour)  </label>
<input type="text" id="salary" name="salary" aria-required="true"><br><br>
<input type="button" class="cancel-button" value="Cancel" onclick="closeForm()">
<input type="button" class="submit-button" value="Submit Form" onclick="submitForm();">
</form>
</div>
</body>
</html>
Menu Code:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Driver Menu')
.addItem('Add Employee', 'showNewEmployeeDialog')
.addToUi();`
};
function handling submission:
function showNewEmployeeDialog() {
var widget = HtmlService.createHtmlOutputFromFile("DatePicker.html");
SpreadsheetApp.getUi().showModalDialog(widget, "Enter Employee Information");
}
const getInfoFromSubmitForm = (form) => {
return form;
}
When I click on menu selection, it opens the modalDialog with all fields visible, but script finishes running. I struggle to collect the info and pass it to the function that would store it as object, and that object would be accessible by other functions in the app script (probably global object declaration, but I need it to be cleared, before it updated, so the new employee info overrides it.)
I think, I'm missing proper onSubmit function and/or eventListener.
Goal is to continue running the script until the form is submitted, make sure all inputs are filled and at least one radio button is clicked. Then send the object {name: value, date: value, employeeType: value (based on which radio button is clicked), and salary value. Once the form is submitted, the dialog closes and global object or function should return the object when function is called.

I have my own portfolio designed with bootstrap4 &I had used modal for feedback,I need to get feedback of visitors,in Google Sheet without Google Form

enter image description here
this image is of my bootstrap modal from modal I wanna to get feedback of visitors
I had hosted this portfolio in HTML I need to get feedback without any database using google sheet.
To give a general answer to your general question:
If you are using a custom HTML form allowing the users to input their feedback, you can incorporate this HTML form into a Google Web App
You can implement a JS script function that will retreive the input values on Form submit client side
+You can call within the JS function a server-side Apps Script function with parameters with google.script.run
Within the Apps script function you can write the input values as desired into a spreadsheet.
Sample:
HTML file index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form id="test-form">
<div>
<label>Field 1</label>
<input type="text" name="field_1" placeholder="Field 1" />
</div>
<div>
<label>Field 2</label>
<input type="text" name="field_2" placeholder="Field 2" />
</div>
<button type="submit" id="submit-form" onclick="myJSFunction()">Submit</button>
</div>
</form>
<script>
function myJSFunction(){
var data=[];
data.push(document.getElementsByName("field_1")[0].value);
data.push(document.getElementsByName("field_2")[0].value);
google.script.run.handleResponse(data);
}
</script>
</body>
</html>
.gs file
function doGet(e){
return HtmlService.createHtmlOutputFromFile('index');
}
function handleResponse(data) {
var sheet = SpreadsheetApp.openById('YOUR SPREADSHEET ID').getSheetByName(SHEETNAME);
sheet.getRange('A1').setValue(data[0]);
sheet.getRange('B1').setValue(data[1]);
}

Apps Script: How to Email Google Sheet file to Email Specified in HTML Service Input?

I am working to build in an HTML Service UI within my Google Sheets file that allows the user to key in the target recipient email address inside the pop-up dialog box within the HTML form. My code is currently not working effectively as an email is not being generated upon run.
JS Code:
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('Index');
SpreadsheetApp.getUi()
.showModalDialog(html, 'Email?');
}
function sendEmail() {
var to = document.getElementbyID("emailInput");
MailApp.sendEmail( {
email: to,
subject: "good morning",
})
}
HTML:
<html>
<head>
<base target="_top">
</head>
<body>
<form id="emailForm">
Send to Email Address:<br> <input type="email" id="emailInput"
name="email" size="40"/><br>
<button onClick="sendEmail()">Send</button>
</form>
</body>
</html>
You can't call a server-side function from the client directly. You need to use the google.script.run API to communicate between the two. Try the following:
// Inside your Apps Script .gs code
// listen for an object sent from the HTML form
function sendEmail(formObj) {
// Extract the email address submitted
var to = formObj.email;
// Send the email
MailApp.sendEmail(to,"good morning", "The email body")
}
...
<body>
<form id="emailForm">
<p>Send to Email Address:</p>
<br>
<input type="email" id="emailInput" name="email" size="40"/> <!-- "name" becomes the key in formObject -->
<br>
<input type="button" value="Send Email" onclick="google.script.run.sendEmail(this.parentNode)" /> <!-- google.script.run allows you to call server-side functions -->
</form>
</body>
...

Google sheets sidebar form - set default values

I am trying to make a spreadsheet sidebar that allows a user to input data to create records, as well as edit them. So far I understand how to create the sidebar and display it. I've got a working form that can submit values.
What I am struggling with is how to pre-populate the forms. Form instance some records are associated with others, and I'd like to have a hidden field to store and eventually submit the associated id. Eventually users should also be able to edit records and I'd like to use the same form and just populate the fields and reuse the same submission flow.
I've tried a few different things found on here and other places, but nothing seems to work.
Here is the HTML for the sidebar template
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<!-- The CSS package above applies Google styling to buttons and other elements. -->
<style>
</style>
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
$('#accountId').val(<? data.accountId ?>);
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(alertSuccess).createContact(formObject);
}
function alertSuccess(message) {
var div = document.getElementById('alert');
div.innerHTML = "<p>" + message + "</p>";
google.script.host.close();
}
</script>
</head>
<body>
<p>Enter Contact Info</p>
<form id="contact" onsubmit="handleFormSubmit(this)">
Account Id: <br>
<input type="number" name="accountId" value="0" id="accountId" /><br>
Name:<br>
<input type="text" name="name"/><br>
Phone Number:<br>
<input type="text" name="phone"/><br>
Email:<br>
<input type="email" name="email"/><br>
Contact Type:<br>
<input type="radio" name="type" value="emergency" checked> Emergency<br>
<input type="radio" name="type" value="guardian" checked> Guardian<br>
<input type="radio" name="type" value="other" checked> Other<br>
<input type="submit" value="Submit" />
</form>
<div id="alert"></div>
</body>
</html>
And the accompanying .gs file:
var AlternativeContact = ObjectModel("AlternativeContacts");
function newContact() {
var htmlOutput = HtmlService.createTemplateFromFile("new_contact");
var id = ACCOUNT_MANAGER.getRange("M4").getValue();
htmlOutput.data = {accountId: id};
UI.showSidebar(htmlOutput.evaluate());
}
function createContact(contactJSON) {
var newContact = new AlternativeContact(contactJSON);
newContact.save();
return "Success!";
}
The first line that uses ObjectModel is creating and ORM around the data sheet.
Thanks for the help!
Couple changes and it seems to be working in a basic way.
First, in the scriptlet, i needed to us the printing tag. so use in stead of . This was causing the value to not be used in the rendered template.
Second, I changed my jQuery to:
$(document).ready(function () {
$("input#accountId").val(<?= data.accountId ?>);
});
If anyone is able to answer, I'd be curious why using the $(document).ready is needed. Doesn't everything in the get run? is it an order of operation thing?

Create a variable if checkbox is checked and write it back to Google spreadsheet

I am trying to create variable if a checkbox is checked in a HTML form.
But could not succeed to write it back.
Here is my complete HTML code "Index.html":-
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<br>
<h1>Add Row To Spreadsheet</h1><br />
<form id='myForm'>
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td></td>
<td><input type="checkbox" name="name1" id="name1"/>A</td>
<td><input type="checkbox" name="name2" id="name2"/>B</td>
<td><input type="checkbox" name="name3" id="name3"/>C</td>
<td><input type="checkbox" name="name4" id="name4"/>D</td>
</tr>
<input type="button" value="Submit" onclick="google.script.run
.withSuccessHandler(google.script.host.close)
.itemAdd(this.parentNode)" />
</table>
<br>
</form>
</html>
Mentioned below is my "Code.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.getSheetByName("Sheet1");
var lastRow = sheet.getLastRow();
var match1 = sheet.getRange("B2").getValue();
var dataRange = sheet.getRange(1, 1,lastRow).getValues();
for(var i=0;i<dataRange.length;i++)
{
if(dataRange[i][0] == match1)
{
if(document.getElementById("name1").checked)
{
days="yes";
sheet.getRange(i+1, 2).setValue(days)
}
}
}
}
Any Help is appreciated, I think html is complete but I am missing something in code.gs Kindly lt me know if you need any further clarification.
Your example should show your form element and submit button in order to verify that you are passing the form element correctly to your google apps script function.
itemAdd() is running on the server side, so it does not have access to DOM elements such as document.getElementById(). You need to access your value of interest from the form element.
Your checkbox elements need to have a value assigned to them
<input type="checkbox" name="name1" id="name1" value="name1val"/>
Your call to itemAdd should pass the form element
.itemAdd(document.getElementById('myForm'));
Once this is done, you should see your form values. You can inspect this by adding the following code.
Logger.log(form)
I believe that the following will provide to access your value.
form["name1"]