Prevent Blank Page and Display Data in Table - javascript

I have a working code in Google Script that is compost on Index.HTML and code.gs actually this code is working if you will test it in your google app script and here it is
Index.HTML
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length; // total elements of results
var table = document.getElementById('output');
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
}
document.writeln("End of results...");
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
Search: <input type="text" id="idSrchTerm" name="search">
<input type="button" value="Search" name="submitButton" onclick="displayMessage()"/>
</div>
<table id ="output">
<tr>
<th>File Details</th>
</tr>
<tr>
<td>
<script>
function handleResults(results){
var length=results.length; // total elements of results
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|"); // split the line |~|, position 0 has the filename and 1 the file URL
document.writeln("<b><a href='"+item[1]+"' target='_blank'>"+item[0]+"</b></a> (Last modified: "+item[2]+")<br/><br/>"); // write result
}
document.writeln("End of results...");
}
</script>
</td>
</tr>
</table>
</body>
</html>
and this is Code.GS
function doGet(e) { // main function
var template = HtmlService.createTemplateFromFile('index.html');
return template.evaluate().setTitle('Search Drive').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function SearchFiles(searchTerm) {
var searchFor ="fullText contains '" + searchTerm + "'";
var names = [];
var files = DriveApp.searchFiles(searchFor);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();
var lm = file.getLastUpdated();
var owner = file.getOwner().getName();
var filesize = file.getSize();
var name = file.getName() +"|~|"+file.getUrl()+"|~|"+lm+"|~|"+owner+"|~|"+filesize;
names.push(name);
Logger.log(file.getUrl());
}
return names;
}
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn);
return resultToReturn;
}
This code is working perfectly but the output of this is everytime i searched a data it transfers me to a new page with the search result.
My Question is How can I display the data in my Table Tag?
Here is the image of where should be the data will put.
Image Link

Related

How to get info from google sheets based on drop list selection?

In my webapp show a drop list that get the sheets name from a google sheets file so I'm trying to get the sheet info based on the selected sheet from the drop list .
the code works but not based on the selection of droplist.
what I did wrong ?
here is the full sample hopefully it will help to identify the issue
CODE.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('dup');
}
function getSheetNames() {
var ss=SpreadsheetApp.getActive();
var shts=ss.getSheets();
var sObj={sA:[]};
shts.forEach(function(sh){
sObj.sA.push(sh.getName());
})
return sObj;
}
function getDataFromServer(e) {
var ss=SpreadsheetApp.getActive();
var data =ss.getSheetByName(e.name).getRange("B2:J22").getValues();
var ar = data.splice(0,1); //add headers
data.forEach(function(f) {
if (~f.indexOf(e.searchtext)) ar.push(f);
});
e['sA']=getSheetNames().sA;
return ar;
}
dup.HTML
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<select id="sel1"></select><label for="sel1">Report Date </label>
</body>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(sObj){
var select=document.getElementById('sel1');
sObj.sA.unshift('Please Select a report date');
select.options.length=0;
for(var i=0;i<sObj.sA.length;i++) {
select.options[i]=new Option(sObj.sA[i],sObj.sA[i]);
}
})
.getSheetNames();
});
const loaded = new Promise((res, rej) => {
google.charts.load('current');
google.charts.setOnLoadCallback(res);
});
let wrapper = null;
async function drawTable(arr) {
await loaded; //wait if charts is not loaded
wrapper = new google.visualization.ChartWrapper({
chartType: 'Table',
dataTable: arr,
containerId: 'table_div',
});
wrapper.draw();
}
function getData(f) {
google.script.run
.withSuccessHandler(drawTable,function(rObj){
$('#sel1').css('background-color','#ffffff');
var select=document.getElementById('sel1');
rObj.sA.unshift('Please Select by Report Date');
select.options.length=0;
for(var i=0;i<rObj.sA.length;i++) {
select.options[i]=new Option(rObj.sA[i],rObj.sA[i]);
}
})
.getDataFromServer(f);
}
</script>
<body>
<form>
<input type="button"id="display"class="btn btn-primary" value="retrieve report Data" onClick="getData(this.parentNode)" />
</form>
<div id="table_div"></div>
</body>
</html>
Here's your html a little better organized. I haven't checked all of the functions but atleast the select tag is inside your form and there's just a simple html structure.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(sObj){
var select=document.getElementById('sel1');
sObj.sA.unshift('Please Select a report date');
select.options.length=0;
for(var i=0;i<sObj.sA.length;i++) {
select.options[i]=new Option(sObj.sA[i],sObj.sA[i]);
}
})
.getSheetNames();
});
const loaded = new Promise((res, rej) => {
google.charts.load('current');
google.charts.setOnLoadCallback(res);
});
let wrapper = null;
async function drawTable(arr) {
await loaded; //wait if charts is not loaded
wrapper = new google.visualization.ChartWrapper({
chartType: 'Table',
dataTable: arr,
containerId: 'table_div',
});
wrapper.draw();
}
function getData(f) {
google.script.run
.withSuccessHandler(drawTable,function(rObj){
$('#sel1').css('background-color','#ffffff');
var select=document.getElementById('sel1');
rObj.sA.unshift('Please Select by Report Date');
select.options.length=0;
for(var i=0;i<rObj.sA.length;i++) {
select.options[i]=new Option(rObj.sA[i],rObj.sA[i]);
}
})
.getDataFromServer(f);
}
</script>
</head>
<body>
<form>
<select id="sel1"></select><label for="sel1">Report Date </label>
<input type="button"id="display"class="btn btn-primary" value="retrieve report Data" onClick="getData(this.parentNode)" />
</form>
</body>
</html>
This is how I've done it. This script starts off by getting a list of all spreadsheets in your account and it populates a drop down on the webapp. You then select the spreadsheet and it goes back to the server to get all of the sheets for the selected spreadsheet. Once you make your selection it then loads that entire sheet on the web app and provides the capability for you to edit the data on that sheet.
Code.gs:
function htmlSpreadsheet(ssO) {
var br='<br />';
var s='';
var hdrRows=1;
var ss=SpreadsheetApp.openById(ssO.id);
var sht=ss.getSheetByName(ssO.name);
var rng=sht.getDataRange();
var rngA=rng.getValues();
s+='<table>';
for(var i=0;i<rngA.length;i++)
{
s+='<tr>';
for(var j=0;j<rngA[i].length;j++)
{
if(i<hdrRows)
{
s+='<th id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="20" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
else
{
s+='<td id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="20" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
}
s+='</tr>';
}
s+='</table>';
s+='</body></html>';
var namehl=Utilities.formatString('<h1>%s</h1>', ss.getName());
var shnamehl=Utilities.formatString('<h2>%s</h2>', sht.getName());
var opO={hl:s,name:namehl,shname:shnamehl};
return opO;
}
function updateSpreadsheet(updObj) {
var i=updObj.rowIndex;
var j=updObj.colIndex;
var value=updObj.value;
var ss=SpreadsheetApp.openById(updObj.id);
var sht=ss.getSheetByName(updObj.name);
var rng=sht.getDataRange();
var rngA=rng.getValues();
rngA[i][j]=value;
rng.setValues(rngA);
var data = {'message':'Cell[' + Number(i + 1) + '][' + Number(j + 1) + '] Has been updated', 'ridx': i, 'cidx': j};
return data;
}
function doGet() {
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
return userInterface.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function getAllSpreadSheets() {
var files=DriveApp.getFilesByType(MimeType.GOOGLE_SHEETS);
var s = '';
var vA=[['Select Spreadsheet',0]];
while(files.hasNext())
{
var file = files.next();
var fileName=file.getName();
var fileId=file.getId();
vA.push([fileName,fileId]);
}
//return vA;
return {array:vA,type:'sel1'};
}
//working on this function right now 2017/11/08
function getAllSheets(ssO) {
var ss=SpreadsheetApp.openById(ssO.id);
var allSheets=ss.getSheets();
var vA=[['Select Sheet']];
for(var i=0;i<allSheets.length;i++)
{
var name=allSheets[i].getName();
vA.push([name]);
}
return {array:vA,type:'sel2'};
}
htmlss.html:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
$('#msg').html('Please wait. Collecting a list of all Spreadsheets...');
google.script.run
.withSuccessHandler(updateSelect)
.getAllSpreadSheets();
});
function updateSS(i,j)
{
var str='#txt' + String(i) + String(j);
var value=$(str).val();
var ssId=$('#sel1').val();
var name=$('#sel2').val();
var updObj={rowIndex:i,colIndex:j,value:value,id:ssId,name:name};
$(str).css('background-color','#ffff00');
google.script.run
.withSuccessHandler(updateSheet)
.updateSpreadsheet(updObj);
}
function updateSheet(data)
{
//$('#success').text(data.message);
$('#txt' + data.ridx + data.cidx).css('background-color','#ffffff');
}
function updateSelect(dtO)
{
$('#sel1').css('background','#ffffff');
$('#sel2').css('background','#ffffff');
$('#msg').html('Spreadsheet List has been updated. Now select a SpreadSheet to display');
var select = document.getElementById(dtO.type);
var vA=dtO.array;
select.options.length = 0;
for(var i=0;i<vA.length;i++)
{
select.options[i] = new Option(vA[i][0],vA[i][vA[i].length-1]);
}
}
function loadSelectSheet()
{
var shId=$('#sel1').val();
var name=$('#sel1').text();
$('#sel1').css('background','#ffff00');
document.getElementById('ssname').innerHTML="";
var ssO={name:name ,id:shId}
google.script.run
.withSuccessHandler(updateSelect)
.getAllSheets(ssO);
}
function displaySelectedSheet()
{
var ssId=$('#sel1').val();
var name=$('#sel2').val();
$('#sel2').css('background','#ffff00');
document.getElementById('shname').innerHTML="";
var ssO={id:ssId,name:name};
google.script.run
.withSuccessHandler(displaySheet)
.htmlSpreadsheet(ssO);
}
function displaySheet(opO)
{
$('#sel2').css('background','#ffffff');
document.getElementById('ssname').innerHTML=opO.name;
document.getElementById('shname').innerHTML=opO.shname;
document.getElementById('sss').innerHTML=opO.hl;
}
console.log('My Code');
</script>
<style>
th{text-align:left}
</style>
</head>
<body>
<div id="msg"></div><br />
<br /><select id="sel1" onChange="loadSelectSheet();"></select>
<br /><select id="sel2" onChange="displaySelectedSheet();"></select>
<div id="ssname"></div>
<div id="shname"></div>
<div id="sss"></div>
</body>
</html>
I did this several years ago but I still use it occasionally.

Scripts conflict

The scripts are working on the first load. However,when I select on the dropdown and the page will reload for the new data on the table based on what I have selected that's the time I won't be able to gather the data when I click in a row. See code below:
code.gs
function doGet()
{
var html=HtmlService.createTemplateFromFile('index');
return html.evaluate();
}
function getSelect() {
var list = SpreadsheetApp.openById('spreadssheetID').getSheetByName("VL Slots").getDataRange().getValues();
var lane = 1;
var select="";
for (var l = 3; l < list.length; l++) {
select+='<option value="' + list[l][lane] + '">'+ list[l][lane] + ' </option>';
}
return select;
}
function getTable(lob) {
var data = SpreadsheetApp.openById('spreadssheetID').getSheetByName("VL Request").getDataRange().getValues();
var rid = 0;
var request = 1;
var table="";
table+='<tr>';
for (var i = 1; i < data.length; i++) {
if (data[i][rid] == lob) {
table+='<td>' + data[i][request] + '</td>';
}
}
table+='</tr>';
return table;
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<script>
function populateSelect(){
google.script.run.withSuccessHandler(onSuccess).getSelect();
}
function onSuccess(select){
document.getElementById("mySelect").innerHTML=select;
}
function polling(){
setInterval(myFunction,2000);
}
function myFunction(){
var lob = document.getElementById("mySelect").value;
google.script.run.withSuccessHandler(onSuccess2).getTable(lob);
}
function onSuccess2(table){
document.getElementById("myTable").innerHTML=table;
}
</script>
<body onload="populateSelect()">
<select id="mySelect" onchange="polling()">
</select>
<table id="myTable">
</table>
<form id="logForm">
<label>Request <span class="required">*</span></label><input type="text" id="request" name="request" class="field-long" placeholder="Request" readonly />
</form>
<script>
var table = document.getElementById('myTable');
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
//rIndex = this.rowIndex;
document.getElementById("request").value = this.cells[0].innerHTML.trim();
};
}
</script>
</body>
</html>
What I want to happen is that I can select on the dropdown and the data will be gathered on the table based on what I have selected and I can click on the row to pass the information in the form.
If I understood correctly, your goal is to click on the value retrieved from the spreadsheet by polling and set this value as a content of your input field "request".
If this is the case, you should incorporate your request inside the onSuccess2 function, so it will occur after the table has been populated with contents from the spreadsheet
Keep in mind that since you retrieve only one value from the sheet, you do not need to loop through row
Modify the html part of your code as following:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<script>
function populateSelect(){
google.script.run.withSuccessHandler(onSuccess).getSelect();
}
function onSuccess(select){
document.getElementById("mySelect").innerHTML=select;
}
function polling(){
setInterval(myFunction,2000);
}
function myFunction(){
var lob = document.getElementById("mySelect").value;
google.script.run.withSuccessHandler(onSuccess2).getTable(lob);
}
function onSuccess2(table){
document.getElementById("myTable").innerHTML=table;
var myTable = document.getElementById('myTable');
var row = myTable.getElementsByTagName("tr")[0];
var cell = row.getElementsByTagName("td")[0];
var request= cell.innerHTML;
row.onclick = createClickHandler(request);
}
var createClickHandler = function(request) {
return function(){
document.getElementById("request").value = request;
};
}
</script>
<body onload="populateSelect()">
<select id="mySelect" onchange="polling()">
</select>
<table id="myTable">
</table>
<form id="logForm">
<label>Request <span class="required">*</span></label><input type="text" id="request" name="request" class="field-long" placeholder="Request" readonly />
</form>
</body>
</html>

Upload files to drive - set new folder ID issue

I'm trying to make an HTML to upload the files to drive. Each upload is creating a new folder. My problem is that I can't set the new folder ID for each upload. It's creating a new folder according to the input + Date. I'm saving a new folder ID on SS. How I can .setParent by the SS cell value on HTML?
Code.gs
/*
Fetch the oAuthToken
*/
function getOAuthToken() {
DriveApp.getRootFolder()
Logger.log(ScriptApp.getOAuthToken())
return ScriptApp.getOAuthToken();
}
function doGet(){
return HtmlService.createTemplateFromFile('drivePicker')
.evaluate()
.setTitle('Upload Files')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function createFolder(form) {
var nameBox = form.subfolder;
var d = new Date();
var time = d.toLocaleTimeString()
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1 ;
var curr_year = d.getFullYear();
var tDate = curr_year + "/" + curr_month + "/" + curr_date + " - " + time;
var dest = DriveApp.getFolderById("main Folder ID").createFolder(nameBox+" "+tDate);
var destID = dest.getId();
var ss = SpreadsheetApp.openById('SS ID');
var sheet = ss.getSheetByName("Name");
sheet.getRange(1,1).setValue(destID);
}
drivePicker.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<style>
#attachmentTable {
background: white;
}
tr th,tr td {
text-align:center;
}
</style>
</head>
<body style='font-family: cursive;'>
<div align="center">
<h1>Please upload the files</h1>
<p><img src="http://www.free-icons-download.net/images/upload-logo-icon-
68584.png" style="width:500px;height:500px;transform:rotate(0deg);margin-
top:50px"></p>
<BR>
<form>
<input type="text" name="subfolder" id="subfolder" placeholder="Your name..">
</form>
<center><button onclick='formSubmit();getOAuthToken()' style="margin-
top:150px;outline:0;" class="btn btn-success">Upload File(s)</button>
</center>
<div class='table-responsive' style="display:none;" id="attachmentTableDiv">
<table id="attachmentTable" class="table table-bordered"
style="width:900px;margin:20px auto;float:none;">
<thead>
<tr style="background:#f1f1f1;">
<th>Title</th>
<th>ID</th>
<th>URL</th>
<th>Date Created</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
function formSubmit() {
google.script.run.withSuccessHandler().createFolder(document.forms[0]);
}
</script>
<script>
var DEVELOPER_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';
var pickerApiLoaded = false;
/**
* Loads the Google Picker API.
*/
function onApiLoad() {
gapi.load('picker', {'callback': function() {
pickerApiLoaded = true;
}});
}
function getOAuthToken() {
google.script.run.withSuccessHandler(createPicker).getOAuthToken();
}
function createPicker(token) {
if (pickerApiLoaded && token) {
var uploadview = new google.picker.DocsUploadView().setParent('NEW FOLDER ID'); //How to set the ID from the SS cell A1 ?????
var picker = new google.picker.PickerBuilder()
.addView(uploadview)
//.addView(all)
.hideTitleBar()
//.setLocale('nl') //--Regional language settings
//.enableFeature(google.picker.Feature.NAV_HIDDEN)
.setOAuthToken(token)
.setSize(536, 350)
.setDeveloperKey(DEVELOPER_KEY)
.setCallback(pickerCallback)
.setOrigin(google.script.host.origin)
.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
.build();
picker.setVisible(true);
} else {
showError('Unable to load the file picker.');
}
}
/**
* A callback function that extracts the chosen document's metadata from the response object.
*/
function pickerCallback(data) {
var action = data[google.picker.Response.ACTION];
if (action == google.picker.Action.PICKED) {
for(var i in data[google.picker.Response.DOCUMENTS]){
var doc = data[google.picker.Response.DOCUMENTS][i];
var id = doc[google.picker.Document.ID];
var url = doc[google.picker.Document.URL];
var title = doc[google.picker.Document.NAME];
var dateCreated = doc[google.picker.Document.LAST_EDITED_UTC];
var date = new Date(dateCreated);
date=date.toLocaleString();
$('#attachmentTable tbody').append("<tr><td>"+title+"</td><td>"+id+"</td><td><a href='"+url+"' target='_blank'>Link</a></td><td>"+date+"</td></tr>");
$('#attachmentTableDiv').show();
}
}
}
</script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>google.load("picker", "1",{callback:function(){pickerApiLoaded
=!0}});</script>
</body>
</html>

How to Pass Textbox Value from One Page to another?

I have 3 Files.
index.html
code.gs and
display.html
index.html
<!DOCTYPE html>
<html>
<head>
<style>
.my_text
{
font-family: Tahoma;
font-size: 13px;
font-weight: normal;
}
</style>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length;
var table = document.getElementById("output");
var count = document.getElementById("count");
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
count.innerHTML = "Total Records Found : " + length;
table.innerHTML +="</br><a href='"+item[1]+"' target='_blank'>"+item[0]+"</a></br> <B>Owner: </B>" +item[3]+ " </br><B>Last modified: </B>"+item[2]+ " </br> <B>File Size: </B>"+item[4]+"</br>";
}
}
function clearBox(elementID)
{
document.getElementById("output").innerHTML = "";
document.getElementById("count").innerHTML = "";
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
<p class = "my_text"><input type="text" id="idSrchTerm" name="search" class = "my_text" >
<input type="button" value="Search Drive" name="submitButton" class = "my_text" onClick="clearBox(); displayMessage();" />
<?var url = getScriptUrl();?><a target="_blank" href='<?=url?>?page=display'><input type="button" value="Open In New Tab" name="submitButton" class = "my_text" onClick="clearBox(); displayMessage();" value='display.html'/></a>
</div>
<div id = "count" class = "my_text">
</div>
<div id ="output" class = "my_text">
</div>
</body>
</html>
code.gs
var scriptProperties = PropertiesService.getScriptProperties();
function doGet(e) {
Logger.log( Utilities.jsonStringify(e) );
if (!e.parameter.page) {
return HtmlService.createTemplateFromFile('index').evaluate();
}
return HtmlService.createTemplateFromFile(e.parameter['page']).evaluate();
return HtmlService.createHtmlOutputFromFile('display');
}
function getScriptUrl() {
var url = ScriptApp.getService().getUrl();
return url;
}
function SearchFiles(searchTerm) {
var searchFor ="fullText contains '" + searchTerm + "'"; //single quotes are needed around searchterm
var userProperties = PropertiesService.getUserProperties();
userProperties.setProperty('SQuery', searchTerm);
var userProperties = PropertiesService.getUserProperties();
var SQuery = userProperties.getProperty('SQuery');
Logger.log(SQuery);
var names = [];
var files = DriveApp.searchFiles(searchFor);
var searchQ = searchTerm;
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();// To get FileId of the file
var lm = file.getLastUpdated();
var OType = file.getOwner().getName();
var fsize = file.getSize()
var name = file.getName()+"|~|"+file.getUrl()+"|~|"+lm+"|~|"+OType+"|~|"+fsize+"|~|"+searchQ; // Im concatenating the filename with file id separated by |~|
names.push(name); // adding to the array
Logger.log(file.getUrl());
}
return names; // return results
}
// Process the form
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn);
return resultToReturn; // return the results
}
display.html
<!DOCTYPE html>
<html>
<head>
<style>
.my_text
{
font-family: Tahoma;
font-size: 13px;
font-weight: normal;
}
</style>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length;
var table = document.getElementById("output");
var count = document.getElementById("count");
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
count.innerHTML = "Total Records Found : " + length;
table.innerHTML +="</br><a href='"+item[1]+"' target='_blank'>"+item[0]+"</a></br> <B>Owner: </B>" +item[3]+ " </br><B>Last modified: </B>"+item[2]+ " </br> <B>File Size: </B>"+item[4]+"</br>";
}
}
function clearBox(elementID)
{
document.getElementById("output").innerHTML = "";
document.getElementById("count").innerHTML = "";
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body onload ="clearBox(); displayMessage();">
<div class="container">
<p class = "my_text">
<input type="text" id="idSrchTerm" name="search" class = "my_text" value = "outing" >
</div>
<div id = "count" class = "my_text">
</div>
<div id ="output" class = "my_text">
</div>
</body>
</html>
actually the output of index.html and output.html are the same they have textbox and the other one has a button. This code is working my only proble here is how can I pass textbox value from index.html to textbox value of display.html
This is what index.html looks like
and this is what display.html looks like
my only target here is to pass textbox value from one site to another and from that I can run my code <body onload> Thats all i need pass textbox value from another textbox from other site TYSM for help
Ty local storage
save the variable
localStorage.setItem('NameOfLocalStorage',Value);
Get the value
localStorage.getItem('NameOfLocalStorage');
You can send data via link, example:
window.location.href = "output.html?" + encodeURIComponent('blah blah bla')
and you can retrive data in output.html
var data = decodeURIComponent(window.location.search.substr(1))

Display Data in New Tab in Same Browser[Working Code]

I have a Google Script that Displays List of Data from Google Drive and this is what it looks like.
This code is working so perfect you just need index.html and code.gs and here is the code for both of them. (So for those who are using google app script in your site this will help.)
index.html
<!DOCTYPE html>
<html>
<head>
<style>
.my_text
{
font-family: Tahoma;
font-size: 13px;
font-weight: normal;
}
</style>
<base target="_top">
<script>
function displayMessage()
{
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length;
var table = document.getElementById("output");
var count = document.getElementById("count");
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
count.innerHTML = "Total Records Found : " + length;
table.innerHTML +="</br><a href='"+item[1]+"' target='_blank'>"+item[0]+"</a></br> <B>Owner: </B>" +item[3]+ "</br><B>Last modified: </B>"+item[2]+ "</br> <B>File Size: </B>"+item[4]+"</br>";
}
}
function clearBox(elementID)
{
document.getElementById("output").innerHTML = "";
document.getElementById("count").innerHTML = "";
}
</script>
<style>
table, th, td
{
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
<p class = "my_text">Search File : <input type="text" id="idSrchTerm" name="search" class = "my_text">
<input type="button" value="Search Drive" name="submitButton" class = "my_text" onClick="clearBox(); displayMessage();"/>
</div>
<div id = "count" class = "my_text"></div>
<div id ="output" class = "my_text">
</div>
</body>
</html>
code.gs
function doGet(e) { // main function
var template = HtmlService.createTemplateFromFile('index.html');
return template.evaluate().setTitle('Search Drive').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function SearchFiles(searchTerm) {
var searchFor ="fullText contains '" + searchTerm + "'";
var names = [];
var files = DriveApp.searchFiles(searchFor);
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();
var lm = file.getLastUpdated();
var OType = file.getOwner().getName();
var fsize = file.getSize()
var name = file.getName()+"|~|"+file.getUrl()+"|~|"+lm+"|~|"+OType+"|~|"+fsize;
names.push(name);
Logger.log(file.getUrl());
}
return names;
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn);
return resultToReturn;
}
}
My only target here is how can I display the result in New Window? I mean I will type any string in textbox and click the button then thats it! the output will display in a new window like for example output.html
TYSM for future help.

Categories