Update from NATIVE sandbox to IFRAME; button not working - javascript

Since the NATIVE sandbox on google apps script is deprecated, I'm switching to IFRAME, which has caused some issues.
The basic outline of the app is that it should allow a user to fill in some information and upload a file (it also makes sure all required fields are completed). Upon submission (by clicking a button), the file should be uploaded to a folder in google drive and a spreadsheet should be updated with the user's information. When I'm in NATIVE, everything works fine. When I set it to IFRAME, nothing happens when I click the submit button.
This is a similar issue to here and here, but neither of them directly address my problem. I also tried following the Google Guide but it didn't help.
Here is my server.gs script:
function doGet(e) {
return template = HtmlService.createHtmlOutputFromFile('form.html').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function uploadFiles(form) {
try {
var dropbox = "Applications";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var CV = form.CV;
var foldername = form.myLastName + ", " + form.myFirstName;
var myFolder = folder.createFolder(foldername);
var file_CV = myFolder.createFile(CV);
var CV_url = file_CV.getUrl();
var sheet_return = addApplicant(form, CV_url);
return "Thank you for your submission."
} catch (error) {
return error.toString();
}
}
function addApplicant(form, CV_url) {
try {
var d = new Date()
var ss = SpreadsheetApp.openByUrl(***INSERT URL TO GOOGLE SHEETS PAGE***);
SpreadsheetApp.setActiveSpreadsheet(ss);
SpreadsheetApp.setActiveSheet(ss.getSheets()[0]);
var sheet = SpreadsheetApp.getActiveSheet();
if (form.visa != "Yes"){
form.visa = "No"
}
sheet.appendRow([d, form.myFirstName, form.myLastName, form.myEmail, form.visa, CV_url]);
} catch (error) {
return error.toString();
}
}
Here is my form.html script:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<!-- You can also include your own CSS styles -->
<link href='https://fonts.googleapis.com/css?family=Bitter' rel='stylesheet' type='text/css'>
<style type="text/css">
.warning {border: 1px solid red !important; background: #fdecb2 !important;}
.hideClass {display:none;}
</style>
<div class="form-style-10">
<title> Application </title>
<form id="myForm" name="myForm">
<fieldset class="fields">
<div class="section"> Personal Information </div>
<div class="inner-wrap">
<label for="myFirstName"> First Name* </label>
<input type="text" id="myFirstName" name="myFirstName" placeholder="" required />
<label for="myLastName"> Last Name* </label>
<input type="text" name="myLastName" placeholder="" required />
<label for="myEmail"> Email* </label>
<input type="email" name="myEmail" placeholder="" required />
<span class="visa-checkbox">
Check if you will require visa assistance. <input type="checkbox" name="visa" value="Yes" />
</span>
</div>
</fieldset>
<fieldset class="fields">
<div class="section"> Documents (pdf format is preferred) </div>
<div class="inner-wrap">
<label for="CV"> CV* </label>
<input type="file" name="CV" required />
</div>
</fieldset>
<p> </p>
<p id="incompleteWarning" class="hideClass"> Please check for incomplete fields and re-submit. </p>
<p id="bePatient" class="hideClass"> Please be patient while the files are being uploaded. Do not close or refresh the form. </p>
<input id="submitbutton" type="button" value="Submit Application" />
</form>
<div id="output" class="hideClass">
<span id="ThankYou" >Thank you for taking the time to complete the application.
</span>
</div>
</div>
<script type="text/javscript">
document.getElementById('submitbutton').addEventListener("click", validatefunction);
function validatefunction() {
document.getElementById('submitbutton').val = 'Submitting...';
//check for required fields
var j = 0;
var form = document.getElementById('myForm');
var elem = form.elements;
for (var i = 0; i < elem.length; i++){
elem[i].className = "";
if (elem[i].value === "" && elem[i].hasAttribute('required')){
elem[i].className = "warning";
j++;
}
}
if (j === 0) {
var btn = document.getElementById('submitbutton');
btn.disabled = true;
document.getElementById('incompleteWarning').style.display = 'none';
document.getElementById('bePatient').style.display = 'inline';
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(this.parentNode);
} else{
document.getElementById('submitbutton').val = 'Submit Application';
document.getElementById('incompleteWarning').style.display = 'inline';
document.getElementById('incompleteWarning').style.color = 'red';
}
};
</script>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').style.display = 'inline';
}
</script>
<style>
input { display:block; margin: 20px; }
</style>
</body>
</html>

Change:
<script type="text/javscript">
To:
<script language="javascript">
I don't know why it doesn't like type="text/javscript"

Related

Google Apps Scripts - My button will not call the javascript function

This is the html code user input form:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div class="marginauto" align="middle">
<style>
.marginauto {
margin: 10px auto 20px;
display: block;
}
</style>
<h1>
<img class="marginauto" align="middle" src="https://drive.google.com/uc?export=view&id=********" alt="*****">
Fabrication Time Record
</h1 >
<h2 class="marginauto" align="middle">
Information
</h2>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname"><br>
<label for="jnum">Job number:</label><br>
<input type="text" id="jnum" name="jnum"><br>
<h2>
Operation
</h2>
<input type="radio" id="cut" name="operation" value="cut">
<label for="cut">Cut</label><br>
<input type="radio" id="drill" name="operation" value="drill">
<label for="drill">Drill</label><br>
<input type="radio" id="fitup" name="operation" value="fitUp">
<label for="fitup">Fit Up</label><br>
<input type="radio" id="weld" name="operation" value="weld">
<label for="weld">Weld</label><br>
<h2>
Comments
</h2>
<input type="text" id="comment"><br>
<br>
<button id="clockin">Clock in</button>
</div>
<script type="text/javascript">
document.getElementById("clockin").addEventListener("click",addLine);
function addLine(){
var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var operation = document.getElementByName("operation");
var entry = {
entry.fn = firstName.value;
entry.ln = lastName.value;
entry.op = operation.value;
}
google.script.run.addEntry(entry);
firstName.value = "";
lastName.value = "";
}
</script>
</body>
</html>
This is the script that takes user inputs from the html and (ideally) transfers them to a google spreadsheet:
function doGet(e){
Logger.log(e);
var html = HtmlService.createHtmlOutputFromFile("userForm");
html.setTitle("Record Time")
return(html)
}
function addEntry(entry){
Logger.log("Someone clicked the button");
var ssid = "1E81*****************QBmW1o4Q";
var ss = SpreadsheetApp.openById(ssid);
SpreadsheetApp.setActiveSpreadsheet(ss);
var database = ss.getSheetByName("Database");
SpreadsheetApp.setActiveSheet(database);
database.appendRow = ([entry]);
}
When I click the button, nothing happens. I am sure that I am calling the correct spreadsheet because I can read and write from the doGet() function, but there seems to be a problem with the addLine() function that I cannot find.
Any help is greatly appreciated, I am very new to web app development.
What I want is for the button to transfer the data from some text input fields to a google spreadsheet. I used multiple different button syntaxes but cannot nothing happens.
You are passing an object to addEntry you should pass an array.
Change
var entry = {
entry.fn = firstName.value;
entry.ln = lastName.value;
entry.op = operation.value;
};
To
var entry = [
firstName.value,
lastName.value,
operation.value
];
Also you have a typo in your client script. Change
var operation = document.getElementByName("operation");
To
var operation = document.getElementsByName("operation");
However getElementsByName returns a node list so to find the checked radio button you need to add this to your client script.
let operations = document.getElementsByName("operation");
let operation = null;
for( let i=0; i<operations.length; i++ ) {
if( operations[i].checked ) {
operation = operations[i];
break;
}
}

Inline error message still displayed after the user adds text to input fields

When users click submit, I've coded an error message to appear under each input field that is missing a value using DOM selectors. I also disabled the email file that opens when submit is clicked, using preventDefault().
However, when the user types into the text area, the messages don't disappear. I tried using a 'keydown' event, but I couldn't get it to work.
HTML code:
<body>
<header class="header">
<form action="mailto:me#fakeemail.com">
<fieldset>
<legend>Personal details</legend>
<p>
<label>
Full name:
<input type="text" name="fullname" id="fullname">
</label>
</p>
<p class="errormsg" id="nameerrormsg">Please enter your name above</p>
<p>
<label>
Street Address:
<input type="text" name="streetaddr" id="streetaddr">
</label>
</p>
<p class="errormsg" id="addrerrormsg">Please enter your street address</p>
</fieldset>
<input type="submit" value="Submit it!" class="submitIt" onsubmit="return checkForm();">
</form>
<br>
<script src="inline-error.js" charset="utf-8"></script>
<div class="returnHome">
Return Home
</div>
</header>
</body>
Javascript code:
var submitIt = document.querySelector(".submitIt");
submitIt.addEventListener("click", function checkForm(event) {
var fNameInput = document.querySelector("#fullname")
var streetAddInput = document.querySelector("#streetaddr")
if (fNameInput.value == "") {
var nameErrorMsg = document.querySelector("#nameerrormsg").style.display = "block";
event.preventDefault();
}
if (streetAddInput.value == "") {
var addrErrorMsg = document.querySelector("#addrerrormsg").style.display = "block";
event.preventDefault();
}
})
To see an immediate result in the code in its current state, hide the error messages before checking the input values.
var submitIt = document.querySelector('.submitIt');
submitIt.addEventListener('click', function checkForm(event) {
var nameErrorMsg = document.querySelector('#nameerrormsg');
var addrErrorMsg = document.querySelector('#addrerrormsg');
nameErrorMsg.style.display = 'none';
addrErrorMsg.style.display = 'none';
var fNameInput = document.querySelector('#fullname');
var streetAddrInput = document.querySelector('#streetaddr');
if (fNameInput.value == '') {
nameErrorMsg.style.display = 'block';
event.preventDefault();
}
if (streetAddrInput.value == '') {
addrErrorMsg.style.display = 'block';
event.preventDefault();
}
});
Having said that, here are some additional suggestions:
Use CSS for styling elements (not JavaScript)
Discourage inline JavaScript
Store DOM elements outside the scope of the event listener so you don't have to query the DOM every time you click
Consider utilizing the required attribute on the inputs for a quick win on styling
So...
<!-- form.html -->
<head>
<link rel="stylesheet" href="form.css">
</head>
<body>
<header class="header">
<form>
<fieldset>
<legend>Personal details</legend>
<p>
<label for="fullname">Full name:
<input type="text" name="fullname" id="fullname" required>
</label>
</p>
<p class="errormsg" id="nameerrormsg">Please enter your name above</p>
<p>
<label for="streetaddr">Street Address:
<input type="text" name="streetaddr" id="streetaddr" required>
</label>
</p>
<p class="errormsg" id="addrerrormsg">Please enter your street address</p>
</fieldset>
<input type="submit" value="Submit it!" class="submitIt">
</form>
</header>
<button id="returnhome">Return Home</button>
<script src="inline-error.js"></script>
</body>
/* form.css */
input:valid {
border: none;
}
input:invalid:required {
border: 1px solid red;
}
.errormsg {
display: none;
}
.show {
display: block;
}
// inline-error.js
var submitIt = document.querySelector('.submitIt');
var nameInput = document.querySelector('#fullname');
var nameError = document.querySelector('#nameerrormsg');
var addrInput = document.querySelector('#streetaddr');
var addrError = document.querySelector('#addrerrormsg');
var returnHome = document.querySelector('#returnhome');
returnHome.addEventListener('click', e => {
e.preventDefault();
history.back();
});
submitIt.addEventListener('click', event => {
const nameValue = nameInput.value;
const addrValue = addrInput.value;
if (!nameValue || !addrValue) {
event.preventDefault();
}
if (!nameValue) {
nameError.classList.add('show');
} else {
nameError.classList.remove('show');
}
if (!addrValue) {
addrError.classList.add('show');
} else {
addrError.classList.remove('show');
}
});

Apps Script WebApp - Update text box field from data from a google sheet

I'm busy with an Apps Script Web App and would like to populate input boxes within the web app with data from a google sheet.
I'm trying to retrieve data when a button is clicked and populate fields within the webapp with the data that is retrieved from the sheet. I just can't seem to get the text box fields to be updated after retrieving the data from google sheets.
Any help would be greatly appreciated.
The code I have so far is:
Code.gs file
function doGet() {
var htmlOutput = HtmlService.createTemplateFromFile("page");
return htmlOutput.evaluate();
}
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
var idx;
var nextLead;
var totalLeads;
var remainingLeads;
function assignLead() {
var ss = SpreadsheetApp.openById("sheetId");
var ws = ss.getSheetByName("leads");
var range = ws.getRange(1, 1, ws.getLastRow(), ws.getLastColumn())
var data = range.getValues();
//console.log(data);
var status = data.map(function (row) {
return row[11];
});
//console.log(status);
idx = status.indexOf("unassigned");
//console.log(idx)
for (var i = 0; i < data.length; i++) {
nextLead = data[idx];
updateStatusAssigned(idx)
}
// console.log(nextLead);
// console.log(data);
}
function updateStatusAssigned(row) {
var ss = SpreadsheetApp.openById("SheetId");
var ws = ss.getSheetByName("leads");
var range = ws.getRange(1, 1, ws.getLastRow(), ws.getLastColumn())
ws.getRange(idx + 1, 12).setValue("assigned")
}
page html file
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<?!= include("page-css") ?>
</head>
<body>
<div>
<!-- Header -->
<div class="header">
<h1>Header</h1>
</div>
<!-- Agent Info -->
<div class="row">
<div>
<p><label for="agnet">Agent Name:</label><input id="agent" type="text" ></input>
<label for="loginTime">Login Time:</label><input id="loginTime" type="text"></input></p>
<p><label for="campaign">Current Campaign:</label><input type="text" id="campaign"></input></p>
<button id="btn-getLead" style= float: right>Get Lead</button>
</div>
<!-- <div>
<button id="btn" style=”float: right”>Get Lead</button>
</div> -->
</div>
<!-- Lead Details Banner -->
<div class="row">
<div class="container">
<h3>Lead Details</h3>
</div>
<!-- Customer Information -->
<div class="flex-container">
<div>
<p>
<h5>Customer Information</h5>
</P>
<label>Name:</label><input type="text" id="name"></input>
<label>Surname:</label><input type="text" id="surname"></input>
<label>ID Number:</label><input type="text" id="id"></input>
<p><label>Address:</label><input type="text" id="add"></input><label>Postal Code:</label><input type="text" id="code"></input></p>
<p><label>Suburb:</label><input type="text" id="sub"></input></P>
<p><label>Postal Address:</label><input type="text" id="p-add"></input></p>
<p><label>Tel Number:</label><input type="tel" id="tel"></input>
<label>Mobile Number:</label><input type="tel" id="cell"></input>
<label>Alternate Number:</label><input type="tel" id="alt"></input></p>
<p>
<label>Disposition</label>
<select id="dispo">
<option> </option>
<option>Wrong Number</option>
<option>No Answer</option>
<option>Win</option>
</select>
</p>
<p>
<button id="submit">Submit</button>
</p>
</div>
<!-- Call Notes -->
<div>
<p>
<h5>Call Notes</h5>
</p>
<textarea rows="15" cols="50" id="notes"></textarea>
</div>
</div>
<?!= include("page-js") ?>
</body>
</html>
page-js file
<script>
document.getElementById("btn-getLead").addEventListener("click",getLeadData);
function getLeadData(){
google.script.run.assignLead()
document.getElementById("name") = nextLead[0];
}
</script>
Modification points:
Unfortunately, the variables declared as the global at Google Apps Script side cannot be used for Javascript side. So nextLead of document.getElementById("name") = nextLead[0]; cannot be used.
I thought that this is due to the reason of your issue.
In this case, withSuccessHandler can be used.
And, I think that document.getElementById("name") = nextLead[0]; occurs an error. In this case, please modify to document.getElementById("name").value = nextLead[0];.
When above points are reflected to your script, it becomes as follows.
Modified script:
Google Apps Script side:
Please modify assignLead() as follows.
From:
for (var i = 0; i < data.length; i++) {
nextLead = data[idx];
updateStatusAssigned(idx)
}
// console.log(nextLead);
// console.log(data);
}
To:
for (var i = 0; i < data.length; i++) {
nextLead = data[idx];
updateStatusAssigned(idx)
}
// console.log(nextLead);
// console.log(data);
return nextLead; // Added
}
Javascript side:
From:
function getLeadData(){
google.script.run.assignLead()
document.getElementById("name") = nextLead[0];
}
To:
function getLeadData(){
google.script.run.withSuccessHandler(nextLead => {
document.getElementById("name").value = nextLead[0];
}).assignLead();
}
Note:
In this modified script, it supposes that your function of assignLead() works fine and nextLead is the correct value you want. Please be careful this.
Reference:
withSuccessHandler(function)

Display toast and clear form after submit

This is a simple contact form using HTML CSS and JavaScript. I am not able to get a message after the form submit button is entered. It redirects me to a page that displays the submitted details and I don't want that to happen obviously. I wish to get a toast message after submit button is clicked, and to reset the form. I have added an extra button just to check functionality for toast. I am really stuck on this!!
Please help!
form demo
(function() {
// get all data in form and return object
function getFormData(form) {
var elements = form.elements;
var honeypot;
var fields = Object.keys(elements).filter(function(k) {
if (elements[k].name === "honeypot") {
honeypot = elements[k].value;
return false;
}
return true;
}).map(function(k) {
if (elements[k].name !== undefined) {
return elements[k].name;
// special case for Edge's html collection
} else if (elements[k].length > 0) {
return elements[k].item(0).name;
}
}).filter(function(item, pos, self) {
return self.indexOf(item) == pos && item;
});
var formData = {};
fields.forEach(function(name) {
var element = elements[name];
// singular form elements just have one value
formData[name] = element.value;
// when our element has multiple items, get their values
if (element.length) {
var data = [];
for (var i = 0; i < element.length; i++) {
var item = element.item(i);
if (item.checked || item.selected) {
data.push(item.value);
}
}
formData[name] = data.join(', ');
}
});
// add form-specific values into the data
formData.formDataNameOrder = JSON.stringify(fields);
formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name
formData.formGoogleSendEmail = form.dataset.email || ""; // no email by default
return {
data: formData,
honeypot: honeypot
};
}
function handleFormSubmit(event) { // handles form submit without any jquery
event.preventDefault(); // we are submitting via xhr below
var form = event.target;
var formData = getFormData(form);
var data = formData.data;
// If a honeypot field is filled, assume it was done so by a spam bot.
if (formData.honeypot) {
return false;
}
disableAllButtons(form);
var url = form.action;
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
// xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
form.reset();
var formElements = form.querySelector(".form-elements")
if (formElements) {
formElements.style.display = "none"; // hide form
}
var thankYouMessage = form.querySelector(".thankyou_message");
if (thankYouMessage) {
thankYouMessage.style.display = "block";
}
}
};
// url encode form data for sending as post data
var encoded = Object.keys(data).map(function(k) {
return encodeURIComponent(k) + "=" + encodeURIComponent(data[k]);
}).join('&');
xhr.send(encoded);
}
function loaded() {
// bind to the submit event of our form
var forms = document.querySelectorAll("form.gform");
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener("submit", handleFormSubmit, false);
}
};
document.addEventListener("DOMContentLoaded", loaded, false);
function disableAllButtons(form) {
var buttons = form.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].disabled = true;
}
}
})();
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<h2 class="content-head is-center">Contact Us!</h2>
<aside>
<p>
We would <em>love</em> to hear from you! </p>
<p>Please use the <b><em>Contact Form</em></b> to send us a message.
</p>
</aside>
<!-- START HERE -->
<link rel="stylesheet" href="https://unpkg.com/purecss#1.0.0/build/pure-min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Style The Contact Form How Ever You Prefer -->
<link rel="stylesheet" href="style.css">
<form class="gform pure-form pure-form-stacked" method="POST" data-email="" action="https://script.google.com/macros/s/AKfycbxud2vvVuUj0YXOasdO50lQwPJc3FnoTZXdNtgRdaYnl70kKDlRO6nS/exec">
<!-- change the form action to your script url -->
<div class="form-elements">
<fieldset class="pure-group">
<label for="name">Name: </label>
<input id="name" name="name" placeholder="What your Mom calls you" />
</fieldset>
<fieldset class="pure-group">
<label for="message">Message: </label>
<textarea id="message" name="message" rows="10" placeholder="Tell us what's on your mind..."></textarea>
</fieldset>
<fieldset class="pure-group">
<label for="email"><em>Your</em> Email Address:</label>
<input id="email" name="email" type="email" value="" required placeholder="your.name#email.com" />
</fieldset>
<fieldset class="pure-group">
<label for="color">Favourite Color: </label>
<input id="color" name="color" placeholder="green" />
</fieldset>
<fieldset class="pure-group honeypot-field">
<label for="honeypot">To help avoid spam, utilize a Honeypot technique with a hidden text field; must be empty to submit the form! Otherwise, we assume the user is a spam bot.</label>
<input id="honeypot" type="text" name="honeypot" value="" />
</fieldset>
<button class="button-success pure-button button-xlarge">
<i class="fa fa-paper-plane"></i> Send</button>
</div>
<!-- Customise the Thankyou Message People See when they submit the form: -->
<div class="thankyou_message" style="display:none;">
<h2><em>Thanks</em> for contacting us! We will get back to you soon!</h2>
</div>
</form>
<div class="toast" id="myToast" data-autohide="false">
<div class="toast-header">
<strong class="mr-auto text-primary">Toast Header</strong>
<small class="text-muted">5 mins ago</small>
<button type="button" class="ml-2 mb-1 close" data-dismiss="toast">×</button>
</div>
<div class="toast-body">
Some text inside the toast body
</div>
</div>
<button type="button" class="btn btn-primary show-toast">Show Toast</button>
<script>
$(document).ready(function() {
$(".show-toast").click(function() {
$("#myToast").toast('show');
});
});
</script>
<!-- Submit the Form to Google Using "AJAX" -->
<script data-cfasync="false" src="form-submission-hanler.js"></script>
<!-- END -->
You can add event on click of button and use reset() to reset the form values. Add following code in your script section:
$('.button-success').on('click', function(e){
e.preventDefault() //This stops page loading
$("#myToast").toast('show'); //Show toast
document.getElementsByName('data-form')[0].reset() //reset field values of the form
})
Add name parameter to your form tag to access it inside this function. (For ex: I have added name as 'data-form')

html sidebar data in not accessible

I have a google sheet, I opened script editor and opened there two files, a script file and an html file. Here is what I have in my script file:
//to load html sidebar
function loadHome() {
const htmlSidebar = HtmlService.createTemplateFromFile("home");
const htmlOutput = htmlSidebar.evaluate();
const ui = SpreadsheetApp.getUi();
ui.showSidebar(htmlOutput);
}
//to create a custom menu
function createMenu(){
const ui = SpreadsheetApp.getUi();
const menu = ui.createMenu("AC Paz");
menu.addItem("Side Registration", "loadHome");
menu.addItem("Order Framing", "loadFraming");
menu.addToUi();
}
//to make sure custom menu is loaded on open
function onOpen(){
createMenu();
}
//to access data passed on html input fields
function userClicked(userInfo){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ws = ss.getSheetByName("Site Information");
ws.appendRow([userInfo.firstName, userInfo.lastName, new Date()])
}
Here is what I have in my html file:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div >
<input id="fn" type="text" >
<label for="fn">First Name</label>
</div>
<div >
<input id="ln" type="text">
<label for="ln">Last Name</label>
</div>
<button id="btn">Add</button>
<script>
document.getElementById("btn").addEventListener("click",doStuff);
function doStuff(){
var userInfo = {}
userInfo.firstName = document.getElementById("fn").value;
userInfo.lastName = document.getElementById("ln").value;
google.script.run.userClicked(userInfo);
document.getElementById("fn").value = "";
document.getElementById("ln").value = "";
}
</script>
Here is my problem: when I type something in input fields and click the button, nothing is passed onto the spreadsheet, but, the entry gets cleared in the input fields.
Try this:
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div >
<input id="fn" type="text" >
<label for="fn">First Name</label>
</div>
<div >
<input id="ln" type="text">
<label for="ln">Last Name</label>
</div>
<button id="btn">Add</button>
<script>
window.onload=function(){
document.getElementById("btn").addEventListener("click",doStuff);
function doStuff(){
var userInfo = {}
userInfo.firstName = document.getElementById("fn").value;
userInfo.lastName = document.getElementById("ln").value;
google.script.run
.withSuccessHandler(function(){
document.getElementById("fn").value = "";
document.getElementById("ln").value = "";
})
.userClicked(userInfo);
}
}
</script>
</body>
</html>
GS:
function userClicked(userInfo){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ws = ss.getSheetByName("Sheet1");
ws.appendRow([userInfo.firstName, userInfo.lastName, new Date()])
}
function showMySideBar() {
SpreadsheetApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('ah1'))
}

Categories

Resources