This is my first approach with js and html coding, please be as much simple as possible!
I want to improve the form developed in my web App making possible to upload image. My goal is to:
Add input type file on my web App
Send the file to server side
Save the file in the G Drive, take the link and save it in Google Sheet
To do this I have already added in my html a file input area, but I'm not sure about how I may manage it in script section.
All the information added in the form are send to server in an object called measureInfo and I want to maintain this routine. When I try to add
measureInfo.media = document.getElementById('fileUpload').files
it doesn't run and console return `Failed due to illegal value in property: media.
Here I report some string of code that may help to answer. If you have some suggests about how manage file in server side with DriveApp please share!
<script>
measureInfo.media= document.getElementById('fileUpload').files
google.script.run.sendToDatabase(measureInfo);
</script>
<form action="#">
<!-- Upload File -->
<div class="file-field input-field">
<div class="btn-large blue darken-3">
<span>Media</span>
<input type="file" id= 'fileUpload' name ='fileUpload'>
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" placeholder = 'Upload Media'>
</div>
</div>
</form>
You could use FileReader.onload event to build an object that can be passed server-side:
const file = document.getElementById('fileUpload').files[0];
const fr = new FileReader();
fr.onload = (e) => {
const data = e.target.result.split(",");
measureInfo.media = {fileName: file.name, mimeType: file.type, data: data[1]};
google.script.run.sendToDatabase(measureInfo);
}
fr.readAsDataURL(file);
Reference:
FileReader.onload
Uploading Multiple Files From Local To Google Drive using Google Apps Script
Here's some code I use for saving receipts:
HTML with JS:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<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(){
google.script.run
.withSuccessHandler(function(rObj){
$('#dt').val(rObj.date);
})
.initForm();
});
function fileUploadJs(frmData) {
var amt=$('#amt').val();
var vndr=$('#vndr').val();
var img=$('#img').val();
if(!amt){
window.alert('No amount provided');
$('#amt').focus();
return;
}
if(!vndr) {
window.alert('No vendor provided');
$('#vndr').focus();
return;
}
if(!img) {
window.alert('No image chosen');
$('#img').focus();
}
document.getElementById('status').style.display ='inline';
google.script.run
.withSuccessHandler(function(hl){
document.getElementById('status').innerHTML=hl;
})
.uploadTheForm(frmData)
}
console.log('My Code');
</script>
<style>
input,textarea{margin:5px 5px 5px 0;}
</style>
</head>
<body>
<h3 id="main-heading">Receipt Information</h3>
<div id="formDiv">
<form id="myForm">
<br /><input type="date" name="date" id="dt"/>
<br /><input type="number" name="amount" placeholder="Amount" id="amt" />
<br /><input type="text" name="vendor" placeholder="Vendor" id="vndr"/>
<br /><textarea name="notes" cols="40" rows="2" placeholder="NOTES"></textarea>
<br/>Receipt Image
<br /><input type="file" name="receipt" id="img" />
<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>
</body>
</html>
GS:
function uploadTheForm(theForm) {
var rObj={};
rObj['vendor']=theForm.vendor;
rObj['amount']=theForm.amount;
rObj['date']=theForm.date;
rObj['notes']=theForm.notes
var fileBlob=theForm.receipt;
var fldr = DriveApp.getFolderById(receiptImageFolderId);
rObj['file']=fldr.createFile(fileBlob);
rObj['filetype']=fileBlob.getContentType();
Logger.log(JSON.stringify(rObj));
var cObj=formatFileName(rObj);
Logger.log(JSON.stringify(cObj));
var ss=SpreadsheetApp.openById(SSID);
ss.getSheetByName('Receipt Information').appendRow([cObj.date,cObj.vendor,cObj.amount,cObj.notes,cObj.file.getUrl()]);
var html=Utilities.formatString('<br />FileName: %s',cObj.file.getName());
return html;
}
function formatFileName(rObj) {
if(rObj) {
Logger.log(JSON.stringify(rObj));
var mA=rObj.date.split('-');
var name=Utilities.formatString('%s_%s_%s.%s',Utilities.formatDate(new Date(mA[0],mA[1]-1,mA[2]),Session.getScriptTimeZone(),"yyyyMMdd"),rObj.vendor,rObj.amount,rObj.filetype.split('/')[1]);
rObj.file.setName(name);
}else{
throw('Invalid or No File in formatFileName() upload.gs');
}
return rObj;
}
function initForm() {
var datestring=Utilities.formatDate(new Date(),Session.getScriptTimeZone(), "yyyy-MM-dd");
return {date:datestring};
}
<script>
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.processForm(formObject);
document.getElementById("myForm").reset();
}
</script>
<script>
function uploadTheForm(theForm) {
var rObj={};
rObj['vendor']=theForm.vendor;
rObj['amount']=theForm.amount;
rObj['date']=theForm.date;
rObj['notes']=theForm.notes
var fileBlob=theForm.receipt;
var fldr = DriveApp.getFolderById(receiptImageFolderId);
rObj['file']=fldr.createFile(fileBlob);
rObj['filetype']=fileBlob.getContentType();
Logger.log(JSON.stringify(rObj));
var cObj=formatFileName(rObj);
Logger.log(JSON.stringify(cObj));
var ss=SpreadsheetApp.openById(SSID);
ss.getSheetByName('Receipt Information').appendRow([cObj.date,cObj.vendor,cObj.amount,cObj.notes,cObj.file.getUrl()]);
var html=Utilities.formatString('<br />FileName: %s',cObj.file.getName());
return html;
}
function formatFileName(rObj) {
if(rObj) {
Logger.log(JSON.stringify(rObj));
var mA=rObj.date.split('-');
var name=Utilities.formatString('%s_%s_%s.%s',Utilities.formatDate(new Date(mA[0],mA[1]-1,mA[2]),Session.getScriptTimeZone(),"yyyyMMdd"),rObj.vendor,rObj.amount,rObj.filetype.split('/')[1]);
rObj.file.setName(name);
}else{
throw('Invalid or No File in formatFileName() upload.gs');
}
return rObj;
}
function initForm() {
var datestring=Utilities.formatDate(new Date(),Session.getScriptTimeZone(), "yyyy-MM-dd");
return {date:datestring};
}
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<base target="_top">
<?!= include('JavaScript'); ?>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<head>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(rObj){
$('#dt').val(rObj.date);
})
.initForm();
});
function fileUploadJs(frmData) {
var amt=$('#amt').val();
var vndr=$('#vndr').val();
var img=$('#img').val();
if(!amt){
window.alert('No amount provided');
$('#amt').focus();
return;
}
if(!vndr) {
window.alert('No vendor provided');
$('#vndr').focus();
return;
}
if(!img) {
window.alert('No image chosen');
$('#img').focus();
}
document.getElementById('status').style.display ='inline';
google.script.run
.withSuccessHandler(function(hl){
document.getElementById('status').innerHTML=hl;
})
.uploadTheForm(frmData)
}
console.log('My Code');
</script>
</head
<body>
<div class="form-row">
<div class="form-group col-md-12">
<h5 style="text-align:center;">Upload Photo</h5>
<div class="form-row">
<div class="form-group col-md-4" style="word-wrap: break-word">
<p3 style="text-align:left; color:red">
Notice! Please doff eyewear & mask and avoid sunlight exposure when taking selfie!</p>
</div>
<div class="form-group col-md-6"><img id="output" width="200" height="200" src="https://www.citypng.com/public/uploads/small/116395943260tji5ordfujy44njydzhlidv8reqpmtun7ggx1oszpz1dcistzxnmag7do6vxkjxphlsgueuurkg9pkpbwgorvv9lratpxm38rp5.png" alt="photo" style="border:gray; border-width:2px; border-style:solid;"/></div>
<div class="form-group col-md-12">
<center>
                        <input class="file-path validate" type="file" id="fileUpload" name="fileUpload" value='fileUpload' accept="image/*" onchange="loadFile(event)">
<script>
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
URL.revokeObjectURL(output.src) // free memory
}
};
</script>
</div>
</body>
</html>
[1]: https://i.stack.imgur.com/98vPf.png
Can anyone tell me how I can make the generated document pick up the data from the forms and put it as their title? I have already looked at the Google Script documentation and so far I have not found anything that can answer me or show me a similar example. Until now I have found relevant subjects and code here, but none have suited my need.
function doGet() {
return HtmlService
.createHtmlOutputFromFile('index')
}
function criarDocument(){
var doc = DocumentApp.create('Doc');
}
function criarSheet(){
var sheet = SpreadsheetApp.create('Sheet');
}
function createPresentation() {
var presentation =
Slides.Presentations.create({"title": "Presentation"});
Logger.log("Created presentation with ID: " + presentation.presentationId);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
body{
background-color: lightblue;
}
</style>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<title>CRIE</title>
<script>
function criarDocument(){
google.script.run.criarDocument();
}
function criarSheet(){
google.script.run.criarSheet();
}
function createPresentation(){
google.script.run.createPresentation();
}
function titulo(){
var st = document.getElementById('student').value;
var te = document.getElementById('teacher').value;
var wo = document.getelementById('work').value;
document.getElementById('student' + 'teacher' + 'work').value;
}
</script>
</head>
<body>
<h1><p align = "center">CRIE SEU ARQUIVO</p></h1>
<div>
<form id = 'form' onsubmit="titulo">
<h2><p align = "center"> Student:</p></h2><p align = "center">
<input type="text" name="estudante" id="student">
<h2><p align = "center">Teacher: </p></h2><p align = "center">
<input type="text" name="professor" id="teacher">
<h2><p align = "center">Work Name</p></h2><p align = "center">
<input type="text" name="trabalho" id="work">
<br><br>
<button class="action" value="Submit" onclick= 'criarDocument()'>Start Document </button>
<button class="action" value="Submit" onclick='criarSheet()'>Start Sheet</button>
<button class="action" value="Submit" onclick='createPresentation()'>Start Presentation</button>
</form>
</div>
</body>
</html>
Here's a simple example of a timestamped text input into a spreadsheet from a sidebar. Don't forget to name your sheet Notes.
Code.gs
function onOpen()
{
loadSideBar();
SpreadsheetApp.getUi().createMenu('My Menu').addItem('loadSidebar', 'loadSideBar').addToUi();
}
function dispText(txt)
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sht=ss.getSheetByName('Notes');
var ts=Utilities.formatDate(new Date(), 'GMT-6', "M/dd/yyyy HH:mm:ss");
var row=[];
row.push(ts);
row.push(txt);
sht.appendRow(row);
return true;
}
function loadSideBar()
{
var userInterface=HtmlService.createHtmlOutputFromFile('sidebar');
SpreadsheetApp.getUi().showSidebar(userInterface);
}
sidebar.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
$('#txt1').val('');
});
function sendText()
{
var txt=$('#txt1').val();
google.script.run
.withSuccessHandler(clearText)
.dispText(txt);
}
function clearText()
{
$('#txt1').val('');
}
console.log("My code");
</script>
</head>
<body>
<textarea id="txt1" rows="12" cols="35"></textarea><br />
<input id="btn1" type="button" value="submit" onClick="sendText();" />
</body>
</html>
So I am currently using google picker, and once the user selects the proper file I want a much smaller html box to appear on top of the picker.
// A simple callback implementation.
function pickerCallback(data) {
if (data.action == google.picker.Action.PICKED) {
var fileId = data.docs[0].id;
window.document.location.href = 'metadata.html';
}
}
Obviously the last line is wrong I was just testing. The issue's that the picker is disappearing once the action is performed and I don't know how to format the html to make it appear as a smaller window, i think its a container but I dont know. It makes sense as to why I just don't know a way around it. I want to mention that the other html is in a separate file and looks like this.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<img src="https://www.artusmode.com/wp- content/uploads/2014/06/geotabC7EC4363A3736759998B3CE5.jpg" alt="Geotab Logo" style="width:250px; height:75px; position: relative; bottom: 9px; left: 70px;">
</head>
<body>
<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>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/themes/cupertino/jquery-ui.css">
<script>
//When the metadata has been successfully saved as document properties
// close the metadata form panel
function onSave() {google.script.host.close()}
</script>
<div>
Department ID: <select id = "drop" style="margin-bottom: 0.25cm;">
<option value="#001">#001---Law</option>
<option value="#002">#002---Sales</option>
<option value="#003">#003---Tech</option>
</select>
<input
type="button"
style="position:relative; left:60px;"
id="set_dep"
value="Set Department"
onclick=" google.script.run.description(document.getElementById('drop').value)"
/>
</div>
<div style="overflow: hidden; padding-right: .5em;">
Date:<input type="text" id = "date" style="margin-left: 60px; margin-bottom: 0.25cm;"/>
<input
type="button"
id="set_date"
value="Set Date"
onclick=" google.script.run.submitDates(document.getElementById('date').value)"
/>
</div>
<div>
Additional Tag: <input type="text" id="metadata" style="overflow: hidden; padding-right: .5em; margin-bottom: 0.25cm;" onkeydown="if(event.keyCode == 13) document.getElementById('set_tag').click();"/>
<input
type="button"
id="set_tag"
value="Set Tag"
onclick="google.script.run.submitDates(document.getElementById('metadata').value ); clearFields();"
/>
<input
type="button"
value="Close"
onclick="google.script.host.close()"
/>
<input
type="button"
value="Clear"
onclick="google.script.run.clear()"
/>
</div>
<script type="text/javascript">
function clearFields() {
document.getElementById("metadata").value="";
}
</script>
<script>
$("#date").datepicker({
showWeek: true,
firstDay: 0,
});
</script>
</body>
</html>
Basically i just want this to appear as a little pop-up that can receive users information. Ignore the methods as those are fine and were used for a previous project. I'm sure it's super obvious but im not used to working with Javascript.
Thanks everyone.
Opening a Bootstrap modal with JQuery can be done with the following
$('#myModal').modal('toggle');
$('#myModal').modal('show');
$('#myModal').modal('hide');
Example
function pickerCallback(data) {
if (data.action == google.picker.Action.PICKED) {
var fileId = data.docs[0].id;
$('#myModal').modal('show')
}
}
Source
I have used nicEditor in my winforms by loading a web browser and loading the nicEditor inside it. By default when the editor loaded and after that I click in the middle of the editor the focus doe not go to nicEditor. But if I click right at the start of the editor, focus is set to the editor. Following is my HTML file code.
<html>
<head>
<script type="text/javascript">
var myInstance = "";
function GetContent() {
//window.alert(""+myInstance);
//var content = tinyMCE.get('tinyMceEditor').getContent();
//content = content.replace("<body>", "<body style=\"font-size:10px;\">");
//var content = nicEditors.get('area3').getContent();
var content = myInstance.instanceById('editor').getContent();
//window.alert(myInstance.instanceById('editor').getContent());
return content;
}
function SetContent(htmlContent) {
setTimeout(function () {
//window.alert(htmlContent);
//nicEditors.get('area3').setContent(htmlContent);
myInstance.instanceById('editor').setContent(htmlContent);
if (htmlContent == undefined || htmlContent == '')
myInstance.instanceById('editor').setContent('');
//tinyMCE.get('tinyMceEditor').readOnly = true;
}, 100);
}
</script>
<script type="text/javascript" src="jscripts/nicEdit.js"></script>
<script type="text/javascript">
bkLib.onDomLoaded(function () {
//myInstance = new nicEditor().panelInstance('editor');
myInstance = new nicEditor({ maxHeight: 388 }).panelInstance('editor');
//nicEditors.allTextAreas()
});
</script>
</head>
<body style="margin-top: 0px; margin-left: 0px;">
<div id="sample">
<textarea id="demo" cols="50" id="editor" name="editor" style="width:295px;" >
</textarea>
</div>
</body>
</html>
Please help.
Its working with this way.
but i am not getting what you are trying to do using below script .
<script type="text/javascript">
bkLib.onDomLoaded(function () {
//myInstance = new nicEditor().panelInstance('editor');
myInstance = new nicEditor({ maxHeight: 388 }).panelInstance('editor');
//nicEditors.allTextAreas()
});
</script>
here is my simple HTML . Now let me know what exactly you want to do .
<html>
<head>
</head>
<body style="margin-top: 0px; margin-left: 0px;">
<div id="sample">
<script type="text/javascript" src="http://js.nicedit.com/nicEdit-latest.js"></script>
<script type="text/javascript">
//<![CDATA[
bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });
//]]>
</script>
<textarea id="demo" cols="50" id="editor" name="editor" style="width:295px;" >
</textarea>
</div>
</body>
</html>
Looking for something like this,
Just let me know if i am wrong anywhere.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<style type="text/css">
.heightClass {
min-height: 338px !important;
}
</style>
<body style="margin-top: 0px; margin-left: 0px;">
<div id="sample">
<script type="text/javascript" src="http://js.nicedit.com/nicEdit-latest.js"></script>
<script type="text/javascript">
//<![CDATA[
bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });
//]]>
$(document).on("focus" , ".nicEdit-selected" , function () {
var parentTag = $( this ).css("height" , "338px");
//$( this ).addClass("heightClass");
//alert(parentTag);
});
</script>
<textarea id="demo" cols="50" id="editor" name="editor" style="width:295px;" >
</textarea>
</div>
</body>
</html>
Trigger the image when i click submt button and in current active tab
<form name="myform" onsubmit="return onsubmitform();">
<input type="submit" name="operation" onclick="document.pressed=this.value" value="GetCATHY"/>
</form>
<script type="text/javascript">
function onsubmitform()
{
if(document.pressed=='GetCATHY')
{
document.pressed.action="img src=a.jpg";
}
}
You can easily do this using jQuery.
However this is pretty simple stuff so I suggest doing a bit of reading and practice on basic html.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#submit").click(function(){
$("#hidden").show();
});
});
</script>
<style type="text/css">
.hidden {
display: none;
}
</style>
</head>
<body>
<form><input type="submit" id="submit"></form>
<div id="hidden" class="hidden">IMAGE</div>
</body>
</html>