Google Script: ui.prompt, submit by pressing enter instead of click button - google-apps-script

How can i submit a ui.prompt in Google Script bypressing "enter key" instead of clicking ok?
Code so far:
function PromptBox()
{
var spreadsheet = SpreadsheetApp.getActive();
var ui=SpreadsheetApp.getUi();
var prompt=ui.prompt("Filter op... ", "Geef je filterwoord op", ui.ButtonSet.OK)
var response=prompt.getResponseText();
var button=prompt.getSelectedButton();
var filterTekst = "";
if (button==ui.Button.OK)
{
return (filterTekst = response);
}
else if(button==ui.Button.CANCEL)
{
ui.alert("Je hebt geannuleerd");
}
}

Roll your own dialog/prompt
You can accomplish this by rolling your own dialog. This a templated html approach so you will have to create some files to implement it. It isn't necessary to do it this way. It happens to be easier for me because all of the css, resource and script files were already created and I find it easier to create the javascript in a file rather than in a string.
Google Script Code:
function showPromptResponse(title,prompt,placeholder){
var title=title || "Prompt Response";//default used for debug
var prompt=prompt || "Enter your Response";//default used for debug
var placeholder=placeholder || "This is the placeholder";//default used for debug
var html="";
html+='<!DOCTYPE html><html><head><base target="_top"><?!= include("res1") ?><?!= include("css1") ?></head><body>';
//html+='<body>';
html+=Utilities.formatString('<h1>%s</h1>', title);
html+=Utilities.formatString('<p>%s</p>',prompt);
html+=Utilities.formatString('<br /><input id="resptext" type="text" size="25" placeholder="%s" />',placeholder);
html+='<br /><input id="okbtn" type="button" value="Ok" onClick="getResponse();" />';
html+='<br /><input id="cancelbtn" type="button" value="Cancel" onClick="google.script.host.close();" />';
html+='<?!= include("promptscript") ?>';
html+='</body></html>';
var ui=HtmlService.createTemplate(html).evaluate();//This is a template
SpreadsheetApp.getUi().showModelessDialog(ui, 'My Prompt');//launch dialog here
}
function loadResponse(resptext) {//This function determines where response is loaded into the spreadsheet.
SpreadsheetApp.getActive().getActiveSheet().getRange('A1').setValue(resptext);
}
function include(filename){//used in the template for loading file content
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
Javascript in a file named promtscript.html
<script>
$(function(){
var input = document.getElementById("resptext");
input.addEventListener("keyup", function(event) {
event.preventDefault();//this isn't required since were not doing a submit but it doesn't seem to hurt anything so I left it.
if (event.keyCode === 13) {//this captures the return keypress
document.getElementById("okbtn").click();
}
});
});
function getResponse(){
var responseText=$('#resptext').val();
console.log(responseText);
if(responseText){
google.script.run.loadResponse(responseText);//send response to google script
}else{
alert('Invalid or No Response');//response if nothing entered
}
}
</script>
The res1.html file is this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
The css1.html file is this:
<style>
body {background-color:#ffffff;}
input{padding:2px;margin:2px;}
</style>
Templated HTML
Client To Server Communication

Related

Upload file and past the link into active cell a spreadsheet

Trying to make a script to upload a file and paste the downloaded file's link into the active cell of a google spreadsheet.
After clicking "Upload" in the modal window, the file is not written to Google Drive and, accordingly, the link is not written to the cell
Code.gs
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('File')
.addItem('Attach...', 'showForm')
.addToUi();
}
function showForm() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi().showModalDialog(html, 'Upload File');
}
function uploadFile(e) {
var newFileName = e.fileName;
var blob = e.file;
var upFile = DriveApp.getFolderById('*FolderID*').createFile(blob).setName(newFileName);
Logger.log(upFile);
var fileUrl = upFile.getUrl();
var formula = '=HYPERLINK("' + fileUrl + '","' + newFileName + '")';
SpreadsheetApp.getActiveRange().setFormula( formula );
return "Uploaded!";
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_center">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form id="myForm" >
Select File: <input type="file" name="file" accept="*" /><br>
File name: <input type="text" name="fileName" /><br><br>
<input type="button" value="Upload" onclick="upload(this.parentNode);" />
</form>
<script>
window.onload=func1;
function func1() {
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
});
}
function upload(obj){
google.script.run.withSuccessHandler(close).withFailureHandler(close).uploadFile(obj);
}
function close(e) {
console.log(e);
google.script.host.close();
}
</script>
</body>
</html>
Issue and workaround:
On December 9, 2021, the file object got to be able to be parsed from the Javascript side to the Google Apps Script side with V8 runtime. But, in this case, this can be used for only Web Apps. In the current stage, the sidebar and dialog cannot parse the file object on the Javascript side. Ref I think that this is the reason of your issue. So, in the current stage, it is required to send the file object as the string and the byte array for the sidebar and the dialog.
In this case, in order to achieve your goal using the current workaround, I would like to propose the following 2 patterns.
By the way, I think that in your Google Apps Script, an error occurs at SpreadsheetApp.getActiveCell().setFormula( formula );. Because SpreadsheetApp has no method of getActiveCell(). In this case, I think that getActiveRange() might be suitable.
Modified script:
In this modification, the file object is converted to the byte array, and the data is sent to Google Apps Script side.
Google Apps Script side:
function showForm() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi().showModalDialog(html, 'Upload File');
}
function uploadFile(e) {
var blob = Utilities.newBlob(...e);
var upFile = DriveApp.getFolderById('*FolderID*').createFile(blob).setName(e[2]);
Logger.log(upFile);
var fileUrl = upFile.getUrl();
var formula = '=HYPERLINK("' + fileUrl + '","' + e[2] + '")';
SpreadsheetApp.getActiveRange().setFormula(formula);
return "Uploaded!";
}
HTML & Javascript side:
<!DOCTYPE html>
<html>
<head>
<base target="_center">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form id="myForm">
Select File: <input type="file" name="file" accept="*" /><br>
File name: <input type="text" name="fileName" /><br><br>
<input type="button" value="Upload" onclick="upload(this.parentNode);" />
</form>
<script>
window.onload = func1;
function func1() {
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
});
}
function upload(obj) {
const file = obj.file.files[0];
// --- For your additional request, I modified below script.
const extension = function(e) {
const temp = e.split(".");
return temp.length == 1 ? "" : temp.pop();
}(file.name);
const filename = `${obj.fileName.value}.${extension}`;
// ---
const fr = new FileReader();
fr.onload = e => {
const obj = [[...new Int8Array(e.target.result)], file.type, filename];
google.script.run.withSuccessHandler(close).withFailureHandler(close).uploadFile(obj);
};
fr.readAsArrayBuffer(file);
}
function close(e) {
console.log(e);
google.script.host.close();
}
</script>
</body>
</html>
Note:
In your script, I thought that the modified script might be a bit complicated. So, I posted the modified script as an answer.
Reference:
Related thread.
How do I convert jpg or png image to Blob via a Google Apps Script Web App?

"cannot read property 'fileName of undefined'" error while uploading file to Google Drive using a html form

The script started to throw an error:
TypeError: Cannot read property 'fileName' of undefined at uploadFile(Code:16:25)
It was working a couple of months back, but now it doesn't, also it sometimes works when used in some other sheet.
Also this is not my code, and i am not a tech guy, i just used this code of someone else. if you could help please tell me what changes do i make in this code.
/* this is the index.html used to get the file to upload*/
<!DOCTYPE html>
<html>
<head>
<base target="_center">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form id="myForm" >
Select File:
<input type="file" name="myfile" accept="*" /><br>
File name: <input type="text" name="fileName" /><br><br>
<input type="button" value="Upload" onclick="upload(this.parentNode);" />
</form>
<script>
window.onload=func1;
function func1() {
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
});
}
function upload(obj){
google.script.run.withSuccessHandler(close).withFailureHandler(close).uploadFile(obj);
}
function close(e) {
console.log(e);
google.script.host.close();
}
</script>
</body>
</html>
/* code.gs function called when file is uploaded*/
function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.createMenu('File')
.addItem('Attach...', 'showForm')
.addToUi();
}
function showForm() {
var app = SpreadsheetApp;
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showModalDialog(html, 'Upload File');
}
function uploadFile(obj) {
var newFileName = obj.fileName; //this is where debug shows the above error
var blob = obj.myfile;
var upFile = DriveApp.getFolderById('1BWcs7RBPDyJQm_R0FLEUxCfRlKTB0uwX').createFile(blob).setName(newFileName);
var fileUrl = upFile.getUrl();
var urlCell = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getActiveCell();
urlCell.setValue(fileUrl);
}
There seems to be a bug related to the curent upgrade of the Apps Script runtime to v8
While this is being fixed, you cannot disable V8 by going from the Apps Script Editor on
Run -> Disable new Apps Script runtime powered by V8
You can alternatively use a different method to upload your file
Sample how to upload your file with fileReader:
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_center">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form id="myForm" >
Select File:
<input type="file" name="myfile" accept="*" /><br>
File name: <input type="text" name="fileName" /><br><br>
<input type="button" value="Upload" onclick="upload(this.parentNode);" />
</form>
<script>
window.onload=func1;
function func1() {
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
});
}
function upload(obj){
var file = obj.myfile.files[0];
var reader = new FileReader();
reader.onload = function(e) {
var obj2 = {
fileName: obj.fileName.value,
mimeType: file.type,
bytes: [...new Int8Array(e.target.result)]
};
google.script.run.withSuccessHandler(close).withFailureHandler(close).uploadFile(obj2);
};
reader.readAsArrayBuffer(file);
}
function close(e) {
console.log(e);
google.script.host.close();
}
</script>
</body>
</html>
code.gs
function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.createMenu('File')
.addItem('Attach...', 'showForm')
.addToUi();
}
function showForm() {
var app = SpreadsheetApp;
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
.showModalDialog(html, 'Upload File');
}
function uploadFile(obj) {
var newFileName = obj.fileName;
var blob = Utilities.newBlob(obj.bytes, obj.mimeType, newFileName);
var upFile = DriveApp.getFolderById('1BWcs7RBPDyJQm_R0FLEUxCfRlKTB0uwX').createFile(blob);
var fileUrl = upFile.getUrl();
var urlCell = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getActiveCell();
urlCell.setValue(fileUrl);
}
Note:
Your error message TypeError: Cannot read property 'fileName' of undefined at uploadFile implies that you tried to run the function uploadFile manually form the editor - without passing it a file as obj parameter - this will lead to the error since without a file there is no fileName (and no fiel data).
The way your code is designed, uploadFile needs to be called from the html form after you upload a file.

How to pass file upload blob from HTML form to server-side Apps Script?

The Google support article example under the Forms heading is broken. From the article:
If you call a server function with a form element as a parameter, the form becomes a single object with field names as keys and field values as values. The values are all converted to strings, except for the contents of file-input fields, which become Blob objects.
I tested this by passing a Form element containing 5 text inputs and a file, then logging Object.keys() on the form object. It returned only the 5 text fields, the file was stripped from the form object. Attempting to assign the file blob directly returned Exception: Invalid argument: blob
How do I pass the file blob from the client-side Form to the server-side Apps Script?
EDIT: To clarify, I also copy-pasted the example provided by Google verbatim. It errors with Exception: Invalid argument: blob.
To reproduce:
Create new Google Apps Script project
Index.html contents:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<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);
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(updateUrl).processForm(formObject);
}
function updateUrl(url) {
var div = document.getElementById('output');
div.innerHTML = 'Got it!';
}
</script>
</head>
<body>
<form id="myForm" onsubmit="handleFormSubmit(this)">
<input name="myFile" type="file" />
<input type="submit" value="Submit" />
</form>
<div id="output"></div>
</body>
</html>
Code.gs contents:
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
function processForm(formObject) {
var formBlob = formObject.myFile;
var driveFile = DriveApp.createFile(formBlob);
return driveFile.getUrl();
}
Publish as Web App
Submit the form with any file
Observe error in View -> Stackdriver Logging -> Apps Script Dashboard
Here's an example:
html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
function fileUploadJs(frmData) {
document.getElementById('status').style.display ='inline';
google.script.run
.withSuccessHandler(updateOutput)
.uploadTheFile(frmData)
}
function updateOutput(info) {
var br='<br />';
var outputDiv = document.getElementById('status');
outputDiv.innerHTML = br + 'File Upload Successful.' + br + 'File Name: ' + info.name + br + 'Content Type: ' + info.type + br + 'Folder Name: ' + info.folder;
}
console.log('My Code');
</script>
<style>
body {background-color:#ffffff;}
input{padding:2px;margin:2px;}
</style>
</head>
<body>
<h1 id="main-heading">Walking Tracks</h1>
<h3>Upload GPS Tracks Files</h3>
<div id="formDiv">
<form id="myForm">
<input name="fileToLoad" type="file" /><br/>
<input type="button" value="Submit" onclick="fileUploadJs(this.parentNode)" />
</form>
</div>
<div id="status" style="display: none">
<!-- div will be filled with innerHTML after form submission. -->
Uploading. Please wait...
</div>
<div id="controls">
<input type="button" value="Close" onClick="google.script.host.close();" />
</div>
</body>
</html>
server code:
function uploadTheFile(theForm) {
var fileBlob=theForm.fileToLoad;
var fldr = DriveApp.getFolderById('FolderId');
var file=fldr.createFile(fileBlob);
var fi=formatFileName(file);
var fileInfo={'name':fi.getName(),'type':fileBlob.getContentType(), 'size':fileBlob.getBytes(), 'folder':fldr.getName()};
return fileInfo;
}
I can confirm that this doesn't work in G-Suite Enterprise. I don't know why because I cannot find documentation that says how Google is serializing the data. It could be a browser/computer security setting or something in G-Suite.
However, there is an easier way to accomplish your need. You can use a Google Form with a file upload question and then create an on form submit trigger/event on it to copy the file to a team/shared drive. Here is sample code if you want to attach the trigger to the Google Form itself:
// ID of the destnation folder to save the file in
var destinationFolderID = "10gkU_2V9iYy-VKudOCOjydEpoepPTgPv"
function saveFileToTeamDrive(e)
{
// a place to save the URL of the uploaded file
var fileID;
// go through all of the responses to find the URL of the uploaded file
e.response.getItemResponses().forEach(function(itemResponse){
// once we find the question with the file
if(itemResponse.getItem().getTitle() == "File Upload Test")
{
// get the file ID from the response
fileID = itemResponse.getResponse();
return;
}
});
// stop if we didn't have one
if(!fileID.length) return;
// get the first index in the array
fileID = fileID[0];
// get the file
var file = DriveApp.getFileById(fileID);
// get the destination folder
var destinationFolder = DriveApp.getFolderById(destinationFolderID);
// make a copy
var newFile = file.makeCopy(destinationFolder);
Logger.log(newFile.getUrl());
}
You can also attach to the on form submit event of a Google Sheet that is linked to a Google Form. I find that way easier cause the Google Sheet on form submit trigger/event includes a JSON of the question/answers so you don't have to iterate all of them to find it. It also means you can re-run a submission if it failed.
WARNING
One important note, if you do either of these things do not give anyone else edit access to the code. This is because as soon as you create and authorize the trigger, anyone who has edit access to the code would be able to use it to gain access to your Google Drive (and anything else the trigger is authorized for). Please see securing a Google Apps Script linked to an authorized trigger so others can edit for more information.

returning data in app script from an HTML input

I am trying to lauch an html form from a google spread sheet using the HTMLService and return data to the script from a select input. I am collecting the data with this line:
-
But I am not sure how to get it back to the script file: I have tried various iterations of:
- city= form.Projects_list.text;
- city= form.Projects_list[0];
- city= form.Projects_list.[0][0];
but none of these seem to be the right handle to the select. The other variables are coming back from the form as desired.
How can I grab that last variable?
HTML File
<b>Add Row To Spreadsheet</b><br />
<form>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#datepicker" ).datepicker();
} );
$( function() {
$( ".widget input[type=submit]" ).button();
$( "button, input, a" ).click( function( event ) {
event.preventDefault();
} );
} );
</script>
<form id = "dateform">
<p>Date: <input type="text" id="datepicker" name ="datepicker"></p><p></p>
Reason for Delay: <input id="reason" name="reason" type="text" />
Last name: <input id="lastName" name="lastName" type="text" />
<input onclick="formSubmit()" type="button" value="Add Row" />
<input onclick="google.script.host.close()" type="button" value="Exit" />
<hr>
<div id = 'pList'>
<table>
<tr>
<td>Select A City</td><td><select id="Projects_list"name ="Projects_list"></select></td>
</tr>
</table>
</div>
</form>
<script type="text/javascript">
function formSubmit() {
google.script.run.getValuesFromForm(document.forms[0]);
google.script.host.close();
}
</script>
<script type="text/javascript">
// Client-side JavaScript that uses the list returned by
// GAS function "getValuesForRngName()" to populate the dropdown.
// This is standard client-side JavaScript programming that uses
// DOM manipulation to get page elements and manipulate them.
function onSuccess(values) {
var opt,
dropDown;
for(i = 0;i < values.length; i +=1){
dropDown = document.getElementById("Projects_list");
opt = document.createElement("option");
dropDown.options.add(opt);
// Remember that GAS Range method "GetValues()" returns
// an array of arrays, hence two array indexes "[i][0]" here.
opt.text = values[i][0];
opt.value = values[i][0];
}
}
function populate(){
google.script.run.withSuccessHandler(onSuccess).getValuesForRngName('Projects20');
}
</script>
<script>
// Using the "load" event to execute the function "populate"
window.addEventListener('load', populate);
</script>
<script>
// Client-side JavaScript that uses the list returned by
// GAS function "getValuesForRngName()" to populate the dropdown.
// This is standard client-side JavaScript programming that uses
// DOM manipulation to get page elements and manipulate them.
function onSuccessx(values) {
var opt,
dropDown;
for(i = 0;i < values.length; i +=1){
dropDown = document.getElementById("Projects_list");
opt = document.createElement("option");
dropDown.options.add(opt);
// Remember that GAS Range method "GetValues()" returns
// an array of arrays, hence two array indexes "[i][0]" here.
opt.text = values[i][0];
opt.value = values[i][0];
}
dropDown = dropDown.options.sort()
}
function populatex(){
google.script.run.withSuccessHandler(onSuccess).getValuesForRngName('Projects20');
}
</script>
<script>
// Using the "load" event to execute the function "populate"
window.addEventListener('loadx', populate);
</script>
App Script File
function demoHtmlServices() {
var ss = SpreadsheetApp.getActiveSpreadsheet(),
html = HtmlService.createHtmlOutputFromFile('changeDateHTML');
setRngName();
ss.show(html);
}
//getValuesFromForm
function getValuesFromForm(form){
var firstName = form.firstName,
lastName = form.lastName,
reason = form.reason,
newDate = form.datepicker,
city= form.Projects_list.text;
sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
SpreadsheetApp.getUi().alert('Test');
sheet.appendRow([lastName, reason, newDate, city]);
var ui = SpreadsheetApp.getUi() ;
alert('Test');
ui.alert('form.Projects_list(0)')
google.script.host.close();
}
// Display the GUI
// Execute this function from the script editor ro run the application.
// Note the call to "setRngName()". This ensures that all newly added
// values are included in the dropdown list when the GUI is displayed
function displayGUI() {
var ss,
html;
setRngName();
ss = SpreadsheetApp.getActiveSpreadsheet();
html = HtmlService.createHtmlOutputFromFile('index').setSandboxMode(HtmlService.SandboxMode.IFRAME);
ss.show(html);
}
// Called by Client-side JavaScript in the index.html.
// Uses the range name argument to extract the values.
// The values are then sorted and returned as an array
// of 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 setRngName() {
var ss = SpreadsheetApp.getActiveSpreadsheet(),
sh = ss.getSheetByName('DropdownValues'),
firstCellAddr = 'A2',
dataRngRowCount = sh.getDataRange().getLastRow(),
listRngAddr = (firstCellAddr + ':A' + dataRngRowCount),
listRng = sh.getRange(listRngAddr);
ss.setNamedRange('20Projects', listRng);
//Logger.log(ss.getRangeByName('Cities').getValues());
}
// For debugging
function test_setRngName() {
setRngName();
}
You can use the value attribute.
document.getElementById("Projects_list").value

google.script.run is not working when using shared script from library

I am working on a script, for which I am calling a function from a library with standalone scripts:
HTML file looks like this:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/themes/cupertino/jquery-ui.css">
<style type="text/css"> .demo { margin: 0px ; color : #AAA ; font-family : arial sans-serif ;font-size : 10pt }
p { color : black ; font-size : 11pt }
.ui-datepicker th {padding:5px;}
.ui-datepicker table {font-size:10px;}
.ui-widget {font-size:12px;}
input{width:100%;}
</style>
<base target="_top">
</head>
<body>
<div class="demo" >
<div style="width:30%;text-align:left;float:left;">
<p> Candidate Email : </p>
<p> Updated Status : </p>
<p> Assigned To :</p>
<p> Date :</p>
</div>
<div style="width:70%;text-align:left;float:left;">
<p> <input class="email" type="text" /></p>
<p><input class="status" type="text" /></p>
<p><input class="assigned" type="text" /></p>
<p><input type="text" name="StartDate" id="startdatepicker" /> </p>
</div>
<input class="submit" type="button" value="Submit" disabled=""/>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<script>
$(document).ready(function(){
$(".email").val(email);
$(".status").val(status);
$(".assigned").val(assigned);
$(document).on('click','input.submit',function(){
submitDates();
});
$( "#startdatepicker" ).datepicker({
showWeek: true,
firstDay: 0,
});
$(document).on('change','#startdatepicker',function(){
if($("#startdatepicker").val()!='')
{
$("input.submit").removeAttr("disabled");
}
else {
$("input.submit").attr("disabled","true");
}
});
});
</script>
<script>
function submitDates() {
var startDate = $("#startdatepicker").val();
var email = $(".email").val();
var status = $(".status").val();
var assigned = $(".assigned").val();
google.script.run
.withSuccessHandler(
// Dates delivered, close dialog
function() {
google.script.host.close();
})
// Display failure messages
.withFailureHandler(
function() {
var div = $('<div id="error" class="error">' + "Please enter the correct Date" + '</div>');
div.after($("#demo"));
})
.statusLogger(email, status, assigned, startDate);*/
}
</script>
</body>
</html>
And gs file looks like this:
function onEdit(event) {
var lSheet = SpreadsheetApp.getActive().getSheetByName("Status Logs");
var sheet = event.source.getSheetByName('Tracker');
var actRng = event.source.getActiveRange();
var editColumn = actRng.getColumn();
var index = actRng.getRowIndex();
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
var dateCol = headers[0].indexOf("Status Change Date");
var updateCol = headers[0].indexOf("Application Status");
var emailCol = headers[0].indexOf("Email");
var assignCol = headers[0].indexOf("Assigned To");
var intType = sheet.getRange(index,updateCol+1).getValue();
var email = sheet.getRange(index,emailCol+1).getValue();
var assignedTo = sheet.getRange(index,assignCol+1).getValue();
if (dateCol > -1 && index > 1 && editColumn == updateCol+1) {
//lSheet.appendRow([email, intType, sheet.getRange(index, dateCol + 1).getValue(),assignedTo]);
var html = HtmlService.createHtmlOutputFromFile('dateDialogue')
.setWidth(300)
.setHeight(200)
.getContent();
var html2 = HtmlService.createHtmlOutput(html + '<script>var email= "'+ email +'";var status="'+ intType +'";var assigned="'+ assignedTo +'";</script>');
SpreadsheetApp.getUi()
.showModalDialog(html2, 'Please enter the Date');
}
}
statusLogger function just append a row in a sheet.
The issue is, google.script.run is not working although google.script.host.close() is working. Any help?
From your question I am concluding you have 2 scripts. One is a document bound script and the another one is stand alone script included in your document bound script as a library.
When you add a script in your project as a library you assign an identifier to it. The library functions can then be called from code.gs using this identifier.
Example:
I have a stand alone script named stackflow which I included in my project as an external library.
The identifier I gave to the library is stackflow
In my standalone script (which is included as a library)
function testLibraryFunction(){
return "successful execution of library function";
}
In my actual project I will try to access library function like this
code.gs
function executeLibraryCode(){
var result = stackflow.testLibraryFunction();
Logger.log(result);
return result
}
In my html file, I will call executeLibraryCode() which will call testLibraryFunction() function from library.
HTML file:
google.script.run
.withSuccessHandler(
// callback function
)
.withFailureHandler(
// callback function
)
.executeLibraryCode();
Also please remove */ from your html file after .statusLogger as mentioned by #ocordova in the comments.