The Java Script Results not showing in HTML - javascript

I wrote a GAS code to check if the employee is In or Not in (extracting data from Google sheets).
The console log give me the right answer but When I click on the button the answer doesn't appear at the front end. Can you help me to troubleshoot on where I went wrong?
<div>
<script>
function onStatus(notify) {
var employee = "John Peter";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var mainSheet = ss.getSheetByName("MAIN");
var data = mainSheet.getDataRange().getValues();
for (var j = 0; j < data.length; j++){
var row = data[j];
var mainSheet2 = row[4];
var mainSheet3 = row[0];
var status = (mainSheet2 =="IN" && mainSheet3 == employee) ;
if (status == true){
var notify = employee +" You Are In"
return notify;
}
}
document.getElementById('status').innerHTML= notify;
}
</script>
<button onclick="onStatus()">Check Status</button>
<font color='Green' id="status" ></font>
</div>

Google provides a very good Client-to-Server Communication guide that I highly suggest you read to get a better understanding of how this works.
You cannot put apps script code (e.g. SpreadsheetApp.getActiveSpreadsheet()) in your frontend scripts. That code has to be run by the apps script server in the backend and you'll then call it using a google.script.run call.
Code.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('Index');
}
function checkStatus() {
var employee = "John Peter";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var mainSheet = ss.getSheetByName("MAIN");
var data = mainSheet.getDataRange().getValues();
for (var j = 0; j < data.length; j++){
var row = data[j];
var mainSheet2 = row[4];
var mainSheet3 = row[0];
var status = (mainSheet2 =="IN" && mainSheet3 == employee) ;
if (status == true){
return employee + " You Are In";
}
}
}
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div>
<button onclick="onStatus()">Check Status</button>
<font color='Green' id="status" ></font>
</div>
<script>
function onStatus() {
google.script.run
.withSuccessHandler(updateStatus) // Send the backend result to updateStatus()
.checkStatus(); // Call the backend function
}
function updateStatus(notify) {
document.getElementById('status').innerHTML= notify;
}
</script>
</body>
</html>

Related

How to fix {"result":"error","error":{"name":"Exception"}} in google apps scripts

.gs
var sheetName = 'Sheet1'
var scriptProp = PropertiesService.getScriptProperties()
function doPost (e){
Logger.log(JSON.stringify(e))
if (!e || !e.parameter){
return;
}
var lock = LockService.getScriptLock();
lock.tryLock(10 * 1000);
try {
var ss = SpreadsheetApp.getActive();
var sheet1 = ss.getSheetByName(sheetName);
var headers = sheet1.getRange(1, 1, 1, sheet1.getLastColumn()).getValues()[0];
var nextRow = sheet1.getLastRow() + 1;
var newRow = headers.map(function(header) {
return header === 'Timestamp' ? new Date() : e.parameter[header]
});
sheet1.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]);
var TEMPLATE_ID = '....ID....'
var PDF_FILE_NAME = newRow[3];
var RESULTS_FOLDER_ID = '....ID....'
var templateFile = DriveApp.getFileById(TEMPLATE_ID);
var copyFile = templateFile.makeCopy();
var copyId = copyFile.getId();
var copyDoc = DocumentApp.openById(copyId);
var copyBody = copyDoc.getActiveSection();
var headerValue;
var activeCell;
var activeRow = sheet1.getRange(nextRow, 1, 1, newRow.length).getValues();
for (var columnIndex = 0; columnIndex < headers.length; columnIndex++){
headerValue = headers[columnIndex]
activeCell = activeRow[0][columnIndex]
copyBody.replaceText('<<' + headerValue + '>>', activeCell);
copyDoc.saveAndClose();
var newFile = DriveApp.createFile(copyFile.getAs('application/pdf'));
copyFile.setTrashed(true);
newFile.setName(PDF_FILE_NAME);
if (RESULTS_FOLDER_ID !== ''){
DriveApp.getFolderById(RESULTS_FOLDER_ID).addFile(newFile)
DriveApp.removeFile(newFile)
}
}
return ..
}
catch (e){
return ContentService ..
}
finally{
lock.releaseLock()
}
}
The purpose of the code is to:
Post data to google sheet
Create a new pdf file every time a new row is submitted using the new row data
I receive the data in the sheet successfully and also the new pdf is created in the drive but with the following errors:
I am supposed to have 4 updated fields but only the first one is updated in the pdf
In the template doc I have: Name1, Name2, Name3, Name4 to be updated as in the sheet header
So when a new row is submitted to the sheet for example with Tom, Mike, John, Andy - I get that in the pdf Tom, Name2, Name3, Name4 (only the first value is updated)
Redirected to {"result":"error","error":{"name":"Exception"}} after submit
.html
<!DOCTYPE html>
<html lang="en">
<body>
<head>
<base target="_top">
</head>
<form action="....URL...." target="_blank" method="POST">
<div>
Name1
<input type="text" required name="Name1">
</div>
<div>
Name2
<input type="text" required name="Name2">
</div>
<div>
Name3
<input type="text" required name="Name3">
</div>
<div>
Name4
<input type="text" required name="Name4">
</div>
<button type="submit">Post</button>
</form>
</body>
</html>
Any help is appreciated. Thanks in advance
How about this modification? Please think of this as just one of several possible answers.
Modification points:
In your script, createFile and setTrashed are run in the for loop of for (var columnIndex = 0; columnIndex < headers.length; columnIndex++){}. In this case, at the 1st loop, a PDF file is created, and copyFile is moved to the trash box. I think that the reason of your issue might be this.
In order to avoid above situation, how about the following modification?
Modified script:
When your script is modified, please modify as follows.
From:
for (var columnIndex = 0; columnIndex < headers.length; columnIndex++){
headerValue = headers[columnIndex]
activeCell = activeRow[0][columnIndex]
copyBody.replaceText('<<' + headerValue + '>>', activeCell);
copyDoc.saveAndClose();
var newFile = DriveApp.createFile(copyFile.getAs('application/pdf'));
copyFile.setTrashed(true);
newFile.setName(PDF_FILE_NAME);
if (RESULTS_FOLDER_ID !== ''){
DriveApp.getFolderById(RESULTS_FOLDER_ID).addFile(newFile)
DriveApp.removeFile(newFile)
}
}
To:
for (var columnIndex = 0; columnIndex < headers.length; columnIndex++){
headerValue = headers[columnIndex]
activeCell = activeRow[0][columnIndex]
copyBody.replaceText('<<' + headerValue + '>>', activeCell);
}
copyDoc.saveAndClose();
var newFile = DriveApp.createFile(copyFile.getAs('application/pdf'));
copyFile.setTrashed(true);
newFile.setName(PDF_FILE_NAME);
if (RESULTS_FOLDER_ID !== ''){
DriveApp.getFolderById(RESULTS_FOLDER_ID).addFile(newFile);
DriveApp.removeFile(newFile);
}
Note:
When you modified the script of Web Apps, please redeploy the Web Apps as new version. By this, the latest script is reflected to the Web Apps. Pleases be careful this.
If I misunderstood your question and this was not the result you want, I apologize. At that time, in order to correctly understand about your situation, can you provide a sample Spreadsheet including your script? By this, I would like to confirm it. Of course, please remove your personal information.

Sending HTML email from spreadsheets

I'm making some improvements to a tutorial. The code sends an email from a Google spreadsheet and take the subject there and marks when the email has been sent, I'm trying to make the message in html.
var EMAIL_SENT = 'Correo Enviado';
//non-duplicate emails with data from the current spreadsheet.
function sendEmails2() {
var templ = HtmlService.createTemplateFromFile('Correo_HTML').evaluate();
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = SpreadsheetApp.getActiveSheet().getRange(2,7).getValue(); // Number of rows
var dataRange = sheet.getRange(startRow, 1, numRows, 3);
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var emailAddress = row[0];
var message = templ.getContent();
var emailSent = row[3];
if (emailSent !== EMAIL_SENT) { // Prevents sending duplicates
var subject = row[2];
MailApp.sendEmail(emailAddress, subject, message);
sheet.getRange(startRow + i, 4).setValue(EMAIL_SENT);
// Make sure the cell is updated right away in case the script is interrupted
SpreadsheetApp.flush();
}
}
}
and I'm writing the HTML code in another window, is super simple but I don't know where could be the trouble
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h2> Test 2</h2>
<p>
Hello World
</p>
<p><strong> learning </strong></p>
</body>
</html>
So how can I get the message in the email with the format in the HTML code?

Adding Elements to Weebly via Javascript Not Working

I have some Javascript code that reads a published Google Sheet and reads it to the webpage. For some reason upon embedding this int Weebly, it just doesn't want to take it. No elements are created at all as far as i can tell. Here is my code, any help is awesome.
<!DOCTYPE html><!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var spData = null;
function doData(json) {
spData = json.feed.entry;
}
function readData(parent) {
var data = spData;
var ScoreObjs = [];
var ScoreObj = new Object();
for(var r=4; r < data.length; r++) {
var cell = data[r]["gs$cell"];
var val = cell["$t"];
console.log(val);
if (cell.col == 1) {
ScoreObj.team1 = val;
}
else if (cell.col == 2) {
ScoreObj.team2 = val;
}
else if (cell.col == 3) {
ScoreObj.score1 = val;
}
else if (cell.col == 4) {
ScoreObj.score2 = val;
ScoreObjs.push(ScoreObj);
ScoreObj = new Object();
}
}
toFormat(ScoreObjs);
}
function toFormat(obj) {
for (var x = 0; x < obj.length; x++)
{
var data = obj[x];
var team1 = data.team1;
var team2 = data.team2;
var score1 = data.score1.toString();
var score2 = data.score2.toString();
var child1 = document.createElement("div");
child1.className = "paragraph";
document.body.appendChild(child1);
var child2 = document.createElement("strong");
child1.appendChild(child2);
var child3 = document.createElement("font");
child3.color = "#FFFFFF";
child3.innerHTML = team1 + " vs " + team2 + "<br />ESEA Scrim";
child2.appendChild(child3);
var child4 = document.createElement("font");
child4.color = "#00FF00";
child4.innerHTML = score1 + ":" + score2;
child1.appendChild(child4);
}
}
$(document).ready(function(){
readData($("#data"));
});
</script>
<script src="https://spreadsheets.google.com/feeds/cells/1BSsomIQwFhifrFB8ybQ6xF0t-KdJNKtCBHotY3X8O98/1/public/values?alt=json-in-script&callback=doData"></script>
</head>
</html>
Change:
<script
src="https://spreadsheets.google.com/feeds/cells/1BSsomIQwFhifrFB8ybQ6xF0t-KdJNKtCBHotY3X8O98/1/public/values?alt=json-in-script&callback=doData"></script>
To:
<script id="data"
src="https://spreadsheets.google.com/feeds/cells/1BSsomIQwFhifrFB8ybQ6xF0t-KdJNKtCBHotY3X8O98/1/public/values?alt=json-in-script&callback=doData"></script>
This could be because the javascript code runs first and renders some problems. I had the same problem.
Include script tags in the footer and not in the head section.
In fact you will find default Weebly script tags below the footer. Add your custom javascript code along with that.
OR
(MORE PREFERABLE)
Create a javascript(.js) file externally upload it to Assets in weebly theme editor and then add it to your HTML header file along with other default weebly script tags.
eg. a javascript file named editsite.js will be added like this (after uploading to assets):
<script type="text/javascript" src="/files/theme/editsite.js"></script>

How pass data between Google Spreadsheet Dialogs?

I'm trying to built an Orders system based on Google Spreadsheet.
I got 1 Spreadsheet ("Order") with 2 sheets ("Orders" and "Products").
First is totally blank (it'll be the sheets where my dialog will put data.
Second is a simple database with a list of articles:
Column A [ID]
Column B [BRAND]
Column C [PRODUCT]
Column D [PIECES]
Column E [PRICE]
Column F [CATEGORY]
Column G [UM]
Column H [VAT]
Column I [SUBCATEGORY]
One brand can have more than one product, in one or more category...
I got
1 Code.gs
and 4 HTML Dialogs
Scelta Categoria.html
Scelta Marchio.html
Scelta Prodotto.html
Ordini.html
Here I don't put Scelta Prodotto.html or Order.html code because first of all I need to pass data between the other dialogs.
I don't wanna a web app if it's possible, but a simple spreadsheet with my custom dialogs working.
I'm not searching for a spreadsheet shared with my costumers but more spreadsheet (every = at the other) one for every my costumer (is a little business, with only 30 costumers, and not all are able to use internet or pc to send me their orders (most of them used call me by phone and dictate me the order).
For them who are more modern as I'm, I start develop those (as Google call in his Script Guide) Scripts Bound to Google Sheets.
code.gs
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Ordine')
.addItem('Apri Maschera', 'ApriSceltaCategoria')
.addToUi();
//doGet();
ApriSceltaCategoria();
}
// Visualizza l'interfaccia grafica.
// Chiamata alla funzione "setRngProdotto()" per assicurare che tutti i nuovi valori sono inclusi nella dropdown list quando l'interfaccia รจ visualizzata.
function ApriSceltaCategoria() {
var ss;
var html;
setRngCat();
ss = SpreadsheetApp.getActiveSpreadsheet();
html = HtmlService.createHtmlOutputFromFile('Scelta Categoria').setSandboxMode(HtmlService.SandboxMode.IFRAME);
ss.show(html);
}
function ApriSceltaMarchio(CategoriaScelta) {
var ss;
var html;
setRngMarchi();
setRngCompleto();
ss = SpreadsheetApp.getActiveSpreadsheet();
html = HtmlService.createHtmlOutputFromFile('Scelta Marchio').setSandboxMode(HtmlService.SandboxMode.IFRAME);
ss.show(html);
}
function ApriSceltaProdotto(ProdottoScelto) {
var ss;
var html;
setRngProdotti();
setRngCompleto();
ss = SpreadsheetApp.getActiveSpreadsheet();
html = HtmlService.createHtmlOutputFromFile('Scelta Prodotto').setSandboxMode(HtmlService.SandboxMode.IFRAME);
ss.show(html);
}
// Chiamata dalla Client-side JavaScript nella pagina.
// Usa l'argomento del nome del range per estrarre i valori. I valori sono quindi ordinati e restituiti come un array di arrays.
function getValuesForRngName(rngName) {
var rngValues = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(rngName).getValues();
return rngValues.sort();
}
//Expand the range defined by the name as rows are added
function setRngCat() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('Prodotti');
var firstCellAddr = 'F2';
var dataRngRowCount = sh.getDataRange().getLastRow();
var listRngAddr = (firstCellAddr + ':F' + dataRngRowCount);
var listRng = sh.getRange(listRngAddr);
ss.setNamedRange('rngListaCategorie', listRng);
}
//Expand the range defined by the name as rows are added
function setRngMarchi() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('Prodotti');
var firstCellAddr = 'B2';
var dataRngRowCount = sh.getDataRange().getLastRow();
var listRngAddr = (firstCellAddr + ':B' + dataRngRowCount);
var listRng = sh.getRange(listRngAddr);
ss.setNamedRange('rngListaMarchi', listRng);
}
//Expand the range defined by the name as rows are added
function setRngProdotto() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('Prodotti');
var firstCellAddr = 'C2';
var dataRngRowCount = sh.getDataRange().getLastRow();
var listRngAddr = (firstCellAddr + ':C' + dataRngRowCount);
var listRng = sh.getRange(listRngAddr);
ss.setNamedRange('rngListaProdotti', listRng);
}
//Expand the range defined by the name as rows are added
function setRngCompleto() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('Prodotti');
var firstCellAddr = 'A2';
var dataRngRowCount = sh.getDataRange().getLastRow();
var listRngAddr = (firstCellAddr + ':I' + dataRngRowCount);
var listRng = sh.getRange(listRngAddr);
ss.setNamedRange('rngListaCompleta', listRng);
}
function OrdinaDati() {
setRngCat();
var rangeToSort = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('rngListaCategorie').getValues();
var selectionArray = rangeToSort.getValues();
rangeToSort.setValues(selectionArray.sort(ordinaLi));
setRngMarchi();
var rangeToSort = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('rngListaMarchi').getValues();
var selectionArray = rangeToSort.getValues();
rangeToSort.setValues(selectionArray.sort(ordinaLi));
setRngProdotto();
var rangeToSort = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('rngListaProdotti').getValues();
var selectionArray = rangeToSort.getValues();
rangeToSort.setValues(selectionArray.sort(ordinaLi));
setRngCompleto();
var rangeToSort = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('rngListaCompleta').getValues();
var selectionArray = rangeToSort.getValues();
rangeToSort.setValues(selectionArray.sort(ordinaLi));
}
function ordinaLi(a,b) {
// Sorts on the first column in the selection ONLY, ascending order.
a=a[0];
b=b[0];
return a==b?0:(a<b?-1:1);
}
/**
* Get the URL for the Google Apps Script running as a WebApp.
*/
function getScriptUrl() {
var url = ScriptApp.getService().getUrl();
return url;
}
/**
* Get "home page", or a requested page.
* Expects a 'page' parameter in querystring.
*
* #param {event} e Event passed to doGet, with querystring
* #returns {String/html} Html to be served
*/
function doGet(e) {
//Logger.log( Utilities.jsonStringify(e) );
Logger.log(e.parameter.page);
var pgToLoad = e.parameter.page;
if (!e.parameter.page) {
Logger.log('!e.parameter.page')
// When no specific page requested, return "home page"
return HtmlService.createTemplateFromFile('Scelta Categoria').evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
Logger.log('there is something for the page');
// else, use page parameter to pick an html file from the script
return HtmlService.createTemplateFromFile('Scelta Categoria').evaluate()
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
Choose Category.html
<!DOCTYPE html>
<html style= "background-color:#B7CEEC;">
<head>
<base target="_top">
<p id="p_cat">Categoria scelta: - </p>
</head>
<body>
<title>TITOLO</title>
<div>
<form>
<hr>
<p style= "text-align: center;">Seleziona una <b style= "color:red;">CATEGORIA</b></p>
<hr>
<table id="Tabella">
</table>
<div style="text-align: center;">
<input type="button" style="font-size: 14px;" id="btnAvanti" value="Avanti -->"
onclick= "google.script.run.withSuccessHandler(google.script.host.close).ApriSceltaMarchio()" />
</div>
</form>
</div>
<hr>
<div style="float:right;">
<input type="button" value="Chiudi"
onclick="google.script.host.close()" />
</div>
<script type="text/javascript">
function estraicategorie (values) {
document.getElementById("btnAvanti").disabled = true;
var categorie = eliminaduplicati(values);
for (i = 0;i < categorie.length; i +=1) {
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var elemlabel = document.createElement('label');
strlabel = "" + categorie [i] + ""
elemlabel.innerHTML = strlabel.bold();
var eleminput = document.createElement('input');
eleminput.setAttribute('type', 'radio');
eleminput.setAttribute('name', 'categorie');
eleminput.setAttribute('value', categorie [i]);
td1.appendChild(elemlabel);
td2.appendChild(eleminput);
tr.appendChild(td1);
tr.appendChild(td2);
document.getElementById('Tabella').appendChild(tr);
}
var ch = document.getElementsByName('categorie');
for (var i = ch.length; i--;) {
ch[i].onchange = function() {
document.getElementById("btnAvanti").disabled = false;
document.getElementById("p_cat").innerHTML = "Categoria scelta: " + this.value;
}
}
}
function eliminaduplicati(a) {
var temp = {};
for (var i = 0; i < a.length; i++)
temp[a[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
function populate() {
google.script.run.withSuccessHandler(estraicategorie).getValuesForRngName('rngListaCategorie');
}
</script>
<script type="text/javascript">
// Using the "load" event to execute the function "populate"
window.addEventListener('load', populate);
</script>
</body>
</html>
Scelta marchio.html
<!DOCTYPE html>
<html style= "background-color:#B7CEEC;">
<head>
<base target="_top">
<p id="p_cat"></p><p id="p_mar"></p>
</head>
<body>
<title>TITOLO</title>
<div>
<form>
<hr>
<p style= "text-align: center;">Seleziona un <b style= "color:red;">MARCHIO</b></p>
<hr>
<table id="Tabella">
</table>
<div style="text-align: center;">
<input style="font-size: 14px;" type="submit" id="btnIndietro" value="<-- Torna>" onclick= "google.script.run.withSuccessHandler(google.script.host.close).ApriSceltaCategoria()" />
<input style="font-size: 14px;" type="submit" id="btnAvanti" value="Avanti -->" onclick= "google.script.run.withSuccessHandler(google.script.host.close).ApriSceltaProdotto()" />
</div>
</form>
</div>
<hr>
<div style="float:right;">
<input type="button" value="Chiudi" onclick="google.script.host.close()" />
</div>
<script type="text/javascript">
function estraimarchi (values) {
document.getElementById("btnAvanti").disabled = true;
var categoria = // HOW CAN I ACHIEVE THIS ???
var elencofiltratoXcat = [];
for (var i = 0; i < values.length; i +=1) {
if (values [i][5] === categoria) {
elencofiltratoXcat.push(values [i]);
}
}
var elencofiltratomarchi = [];
for (i = 0; i < elencofiltratoXcat.length; i +=1) {
elencofiltratomarchi.push(elencofiltratoXcat[i][1]);
}
var marchi = [];
marchi = eliminaduplicati(elencofiltratomarchi);
marchi.sort();
for (i = 0;i < marchi.length; i +=1) {
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var elemlabel = document.createElement('label');
strlabel = "" + marchi [i] + "";
elemlabel.innerHTML = strlabel.bold();
var eleminput = document.createElement('input');
eleminput.setAttribute('type', 'radio');
eleminput.setAttribute('name', 'marchi');
eleminput.setAttribute('value', marchi [i]);
td1.appendChild(elemlabel);
td2.appendChild(eleminput);
tr.appendChild(td1);
tr.appendChild(td2);
document.getElementById('Tabella').appendChild(tr);
}
var ch = document.getElementsByName('marchi');
for (var i = ch.length; i--;) {
ch[i].onchange = function() {
document.getElementById("btnAvanti").disabled = false;
document.getElementById("p_cat").innerHTML = "Categoria: " + categoria;
document.getElementById("p_mar").innerHTML = "Marchio: " + this.value;
}
}
}
function populate(){
google.script.run.withSuccessHandler(estraimarchi).getValuesForRngName('rngListaCompleta');
}
function eliminaduplicati(a) {
var temp = {};
for (var i = 0; i < a.length; i++)
temp[a[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
</script>
<script>
// Using the "load" event to execute the function "populate"
window.addEventListener('load', populate);
</script>
</body>
</html>
As I commented in the code, the problem is when I try to pass values between dialogs. I try to use in Scelta Categoria.html
document.getElementById("btnAvanti").disabled = false;
document.getElementById("p_cat").innerHTML = "Categoria scelta: " + this.value;
var userProperties = PropertiesService.getUserProperties();
var userCat = userProperties.setProperty('SceltaCategoria', '' + this.value + '');
but nothing to do.
Sure I can open another sheet and put user choice in A1 for example, then hide the sheet, but I reputate more quick if I can use variables.
Any suggestion, try to remain in this context and not in web app ?
Thanx in advance and sorry for my bad english.

Getting blank screen after running Google web app script

I am working on a check-in app though Google Sheets and want to make a search function that that takes a sport name as input in an HTML form and then returns information about the sport from the sheet in a HTML table. However, when I try to test the web app, nothing happens. How can I fix this?
Here is my code:
Index.html
<!DOCTYPE html>
<html>
<head>
<?!= HtmlService.createHtmlOutputFromFile('Stylesheet').getContent(); ?>
</head>
<body>
<fieldset id="tasks-panel">
<legend>Sports</legend>
<form name="sport-form" id="sport-form">
<label for="sport-name">Search a sport by name:</label>
<input type="text" name="sport-name" id="sport-name" />
<button onclick='addTable()' id='submit-button'>Press this</button>
</form>
<p>List of things:</p>
<div id="toggle" style="display:none"></div>
</fieldset>
<?!= HtmlService.createHtmlOutputFromFile('Javascript').getContent(); ?>
</body>
</html>
Javascript.html
<script>
function addTable() {
var sportInput = $('sport-name').value();
var columnNames = ["Names", "Times"];
var dataArray = google.script.run.getSportData(sportInput);
var myTable = document.createElement('table');
$('#divResults').append(myTable);
var y = document.createElement('tr');
myTable.appendChild(y);
for(var i = 0; i < columnNames.length; i++) {
var th = document.createElement('th'),
columns = document.createTextNode(columnNames[i]);
th.appendChild(columns);
y.appendChild(th);
}
for(var i = 0 ; i < dataArray.length ; i++) {
var row= dataArray[i];
var y2 = document.createElement('tr');
for(var j = 0 ; j < row.length ; j++) {
myTable.appendChild(y2);
var th2 = document.createElement('td');
var date2 = document.createTextNode(row[j]);
th2.appendChild(date2);
y2.appendChild(th2);
}
}
}
</script>
Code.gs
//Setting up global variables
var ss = SpreadsheetApp.openById("-spreadsheetID-");
var sheet = ss.getSheetByName("Sheet1");
var sportsFromSheet = sheet.getRange("D4:D12");
var namesFromSheet = sheet.getRange("B4:B12").getValues();
var timesFromSheet = sheet.getRange("A4:A12").getValues();
var NAMES = [];
var TIMES = [];
var OUTPUT = [];
//doGet function
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate()
.setTitle('Check In Data')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
//Gets both names and times of checked-in people
function getSportData(input) {
var sportInput = input;
getNamesInSport(sportInput);
getTimesInSport(sportInput);
OUTPUT = [
[NAMES],
[TIMES]
];
Logger.log(OUTPUT);
return OUTPUT;
}
//Puts the names of every person from an inputted sport into an array.
function getNamesInSport(input) {
var data = sportsFromSheet.getValues();
for (var i = 0; i < data.length; i++) {
if(data[i] == input){
NAMES.push(namesFromSheet[i][0]);
}
}
}
//Puts the times of every person from an inputted sport into an array.
function getTimesInSport(input){
var data = sportsFromSheet.getValues();
for (var i = 0; i < data.length; i ++) {
if(data[i] == input){
TIMES.push(timesFromSheet[i][0]);
}
}
}
JQuery id selectors must be prefixed with # so to grab the value from the the 'sport-name' input you'll need to select it using
var sportInput = $('#sport-name').val();
Additionally, as Robin comments above, if you want to use the JQuery library you'll need to load it, the code you've shown indicates you might not have done this?
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
Although if this were the case you'd probably be seeing a '$ is not defined' error straight away.

Categories