Are the csv files generated with parseCsv stored somewhere? - google-apps-script

I'm doing a web in google script.
I have done the following search method:
https://script.google.com/macros/s/AKfycbzxWqtu9bIhTXb2zP9fsOoFFqe3St1T1C91ZDVu747GCWxrR1c/exec
my code Codigo.gs is:
function doGet(e) {
Logger.log(Utilities.jsonStringify(e));
if(!e.parameter.page){
return HtmlService.createTemplateFromFile("Index").evaluate();
}
var template=HtmlService.createTemplateFromFile(e.parameter.page)
template.action=ScriptApp.getService().getUrl();
return template.evaluate();
return HtmlService
.createHtmlOutputFromFile('Index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
/***************************** buscar asignado de trabajo ********************************************/
function get_AsignadoSS(k){
var sPers_asignado=k.pers_asignado;
var sReg_Asig="LIMA";
var contenido_ul="";
var spreadsheetId_r = '1ykYOd5PWP5aZEREnRIqkPMLT1pSYrcRA6mfQHl7bL4I'; // Please set the spreadsheet ID.
var targetSheet_r = 'Personal'; // Please set the sheet name.
if(sPers_asignado!="") {
var query_r = 'select A, B where ( B contains "'+sPers_asignado.toUpperCase()+'" or A contains "'+sPers_asignado.toUpperCase()+'" ) AND E = "'+sReg_Asig+'"'; // Please set the query for retrieving the values.
var ss_r = SpreadsheetApp.openById(spreadsheetId_r);
var sheetId_r = ss_r.getSheetByName(targetSheet_r).getSheetId();
var url_r = "https://docs.google.com/spreadsheets/d/" + spreadsheetId_r + "/gviz/tq?gid=" + sheetId_r + "&tqx=out:csv&tq=" + encodeURIComponent(query_r);
var res_r = UrlFetchApp.fetch(url_r, {headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}});
var row = Utilities.parseCsv(res_r.getContentText());
//https://docs.google.com/spreadsheets/d/1z4izqpus1yE6rZiqY1ttCEYA3NO3d7J3bZ4oFgQW330/gviz/tq?gid=Usuarios&tqx=out:csv&tq=encodeURIComponent('select A, B where ( B contains "li" )')
if(row.length>6){
var maximo=7;
}else{
var maximo=row.length;
}
//var contenido_ul=sCodigo_site;
var contenido_ul=contenido_ul+"<ul id='country-list' class='list-group'>";
for (var i = 1; i < maximo; i++) {
var nombre_site = row[i][1].toString();
var pasar_nom_site='"'+row[i][1].toString()+'"';
var contenido_ul=contenido_ul+"<li class='list-group-item' style='text-align: left' onClick='selectCountry("+pasar_nom_site+");'>"+nombre_site+"</li>";
}
var contenido_ul=contenido_ul+"</ul>";
}
if(sPers_asignado=="") {
var contenido_ul="";
}
return contenido_ul;
}
and my code Index.html is
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
function buscar_asignado(){
google.script.run.withSuccessHandler(get_Asignado).get_AsignadoSS(document.forms[0]);
}
function get_Asignado(data){
//alert("tt");
$("#suggesstion-box-asignado").show();
$("#suggesstion-box-asignado").html(data);
}
function selectCountry(codigo) {
$("#pers_asignado").val(codigo);
$("#suggesstion-box-asignado").hide();
}
/*----------------codigo esencial para conectar con codigo.GS----------------------*/
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);
</script>
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.bootstrap4.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/fixedheader/3.1.6/css/fixedHeader.dataTables.min.css">
</head>
<body>
<div class="modal-header" style="background-color: red;color: white;padding-top:5px;padding-bottom:5px">
<CENTER><label style="font-size: 30px;font-family: monospace;font-weight: normal;color:white">ACTIVIDADES</label></CENTER>
</div>
<div id="todo_contenido"style="display:block">
<center><br><br>
<div class="modal-content" style="width:95%">
<div class="modal-body">
<form id="datosTrabajo" name="datosTrabajo">
<div class="form-group row">
<label for="pers_asignado" class="col-sm-2 col-form-label">Asignado:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="pers_asignado" name="pers_asignado" onkeyup="buscar_asignado();" placeholder="Nombre Asignado..." style="background-color: white">
<div id="suggesstion-box-asignado" style="position: absolute;z-index: 1"></div>
</div>
<label for="tipo_trabajo" class="col-sm-2 col-form-label">Tipo Trabajo:</label>
<div class="col-sm-4">
<select class="form-control" id="tipo_trabajo" name="tipo_trabajo" >
<option value="">Select Tipo Equipo:</option>
<option value="ATPs">ATPs</option>
<option value="Caceria Interferencia">Caceria Interferencia</option>
<option value="Desbalance RTWP">Desbalance RTWP</option>
<option value="Respaldo Baterias">Respaldo Baterias</option>
<option value="Site Audit">Site Audit</option>
<option value="Trabajos TX">Trabajos TX</option>
<option value="Prueba de Llamadas">Prueba de Llamadas</option>
<option value="PIM Logico">PIM Logico</option>
<option value="Administrativo">Administrativo</option>
<option value="OTROS">OTROS</option>
</select>
</div>
</div>
</form>
</div>
</div>
<br>
</center>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.3/js/dataTables.responsive.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.3/js/responsive.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/fixedheader/3.1.6/js/dataTables.fixedHeader.min.js"></script>
</body>
</html>
Then each time a letter is entered, a new search is made. In this case the search becomes normal, since it only occurs in 100 records. But my question is whether it is every time a new query is made (every time a digit is entered). These csv files are stored somewhere. The problem I have is that I have a more extensive code, which searches 6000 records; but you are not doing the search, and there are personnel who connect to this website to enter information and are having problems.
Or will there be some other way to do this type of search in Google Script?

parseCsv() - Returns a tabular 2D array representation of a CSV string. So
var A=Utilities.parseCsv(csvdata);
sheet.getRange(1,1,A.length,A[0].length).setValues(A);
will put the data into sheet.
The csv and the 2d array's are not stored anywhere unless you stored somewhere.

Related

upload files into google drive folder from side bar UI

I am trying to make web app as a sidebar in spreadsheet using HTML5, Bootstrap 5 & JavaScript to make entry of data easier . I managed to go through the entire process But the problem that I can't make the button upload files into google drive folder and return with the url back.
the link of sheet working with.
I think the problem in this variable from html script but I don't know what is it
var url = document.getElementById("transaction-file").addEventListener('click',
function(a){
google.script.run.uploadFiles(this.parentNode)
});
https://docs.google.com/spreadsheets/d/1D-tEPsUJqGbCHrF8CYQlPu_ZhmVIGDYEojHfO0_7rW4/edit?usp=sharing
google script code
function loadForm() {
const htmlForSidebar = HtmlService.createTemplateFromFile("uform");
const htmlOutput = htmlForSidebar.evaluate();
htmlOutput.setTitle("Winter 2021");
const ui = SpreadsheetApp.getUi();
ui.showSidebar(htmlOutput);
}
function createMenu(){
const ui = SpreadsheetApp.getUi();
const menu = ui.createMenu("My Forms");
menu.addItem("Show UserForm", "loadForm");
menu.addToUi();
}
function onOpen(){
createMenu();
}
function uploadFiles(files){
var file = files.myFile;
var folder = DriveApp.getFolderById('1gaNAb1s8j7wmotvRUJbg4yfJOFNdZYo5');
var createFile = folder.createFile(file);
return createFile.geturl();
}
function addNewRow(rowData) {
const currentDate = new Date();
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("Sheet1");
ws.appendRow([currentDate, rowData.trxDate, rowData.account, rowData.trxID, rowData.amount, rowData.url, rowData.comment]);
return true;
}
function getDropDownArray(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("Ref");
return ws.getRange(2, 1, ws.getLastRow()-1, 1).getValues();
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<div class="container pt-3">
<h4 class="border-bottom pb-2 mb-4">Donations' Registration <span class="badge bg-secondary">Form</span></h4>
<div id="userform">
<div class="mb-3">
<label for="transaction-date" class="form-label">Transaction Date</label>
<input type="date" class="form-control" id="transaction-date" required>
<div class="invalid-feedback">Please enter valid date.</div>
</div>
<div class="mb-3">
<label for="transaction-account" class="form-label">Account</label>
<select class="form-select" id="transaction-account" required aria-label="select account" required>
</select>
<div class="invalid-feedback">Please enter valid account.</div>
</div>
<div class="mb-3">
<label for="transaction-id" class="form-label">Transaction ID</label>
<input type="text" class="form-control" id="transaction-id" required>
<div class="invalid-feedback">Please enter valid ID.</div>
</div>
<div class="mb-3">
<label for="transaction-amount" class="form-label">Amount</label>
<input type="number" class="form-control" id="transaction-amount" required>
<div class="invalid-feedback">Please enter valid amount without any service fees.</div>
</div>
<div class="mb-3">
<label for="transaction-file" class="form-label">url</label>
<input type="file" class="form-control" id="transaction-file" name="myFile" aria-label="file example" required>
<div class="invalid-feedback">Please upload right file.</div>
</div>
<div class="mb-3">
<label for="transaction-memo" class="form-label">Memo</label>
<textarea class="form-control" id="transaction-memo" rows="1"></textarea>
</div>
<div class="mb-3">
<button class="btn btn-primary" id="mainButton">Add to Database</button>
</div>
</div>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
-->
<script>
function afterButtonClicked(){
if(validate()){
var trxDate = document.getElementById("transaction-date");
var account = document.getElementById("transaction-account");
var trxID = document.getElementById("transaction-id");
var amount = document.getElementById("transaction-amount");
var url = document.getElementById("transaction-file");
var comment = document.getElementById("transaction-memo");
var rowData = {trxDate: trxDate.value, account: account.value, trxID: trxID.value, amount: amount.value, url: url.value, comment: comment.value};
google.script.run.withSuccessHandler(afterSubmit).addNewRow(rowData);
} else {
//handle this later
}
}
function afterSubmit(e){
clearFields(["transaction-date", "transaction-account", "transaction-id", "transaction-amount", "transaction-file", "transaction-memo"]);
}
function clearFields(fields){
fields.forEach(function(field){
var el = document.getElementById(field);
el.value = "";
});
}
function validate(){
var fieldsToValidate = document.querySelectorAll("#userform input, #userform select");
//is-invalid
Array.prototype.forEach.call(fieldsToValidate,function(el){
if(el.checkValidity()){
el.classList.remove("is-invalid");
} else {
el.classList.add("is-invalid");
}
});
return Array.prototype.every.call(fieldsToValidate,function(el){
return el.checkValidity();
});
}
function afterSidebarLoads(){
google.script.run.withSuccessHandler(afterDropDownArrayReturned).getDropDownArray();
}
function afterDropDownArrayReturned(arrayOfArrays){
var account = document.getElementById("transaction-account");
arrayOfArrays.forEach(function(r){
var option = document.createElement("option");
option.textContent = r[0];
account.appendChild(option);
});
}
document.getElementById("mainButton").addEventListener("click",afterButtonClicked);
google.script.run.uploadFiles(this.parentNode);
document.addEventListener("DOMContentLoaded",afterSidebarLoads);
</script>
</body>
</html>

Google Web App - Search box to filter the data from Google Spread sheet

Thanks in advance. Just to start with, I am not a coder, but I keep on researching. I made a search Web App to filter the data from Google spreadsheet which has more than 2000+ rows, which keeps on increasing day by day and around 135 columns for different Institutes. So, it was messy to search in that Google sheet, and hence I created this web app.
Everything is working smoothly until the records were around 1200 rows but now I am facing an issue to display more than 2000 records. The Web App Search box displays the list based on the key we pressed. Like if we enter "A", it will display the names starting from the alphabet "A". So, what I do is, I keep on adding the new tags (Institute names) and it works well but now suddenly after adding few records, it says unable to open the file.
Request you to please look into this and let me know any alternative or correct this code to work smoothly regardless of the numbers of tags or rows. Thank you so much.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o" crossorigin="anonymous"></script>
<!-- <link href="path/to/select2.min.css" rel="stylesheet" />
<script src="path/to/select2.min.js"></script> -->
<!-- <link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script> -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Autocomplete using Jquery</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>
<!--##JAVASCRIPT FUNCTIONS ---------------------------------------------------- -->
<script type="text/javascript">
$( function() {
var searchtext = [
"Australian Catholic University",
"Australian National University (ANU)",
"Central Queensland University",
"Royal Melbourne Institute of Technology (RMIT)",
/*Like this we have more that 2000 names of Institutes*/
];
$( "#searchtext" ).autocomplete({
source: searchtext
/* #the tags is the id of the input element
source: tags is the list of available tags*/
});
} );
//PREVENT FORMS FROM SUBMITTING / PREVENT DEFAULT BEHAVIOUR
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, true);
// $(document).ready(function() {
// $('.js-example-basic-single').select2();
// });
function myFunction() {
document.getElementById("searchtext").size = "70";
}
//HANDLE FORM SUBMISSION
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(createTable).processForm(formObject);
// document.getElementById("search-form").reset();
}
//CREATE THE DATA TABLE
function createTable(dataArray) {
if(dataArray && dataArray !== undefined && dataArray.length != 0){
var result = "<table class='table table-sm table-striped' id='dtable' style='font-size:0.8em'>"+
"<thead style='white-space: nowrap'>"+
"<tr>"+ //Table headings
"<th scope='col'>Institution</th>"+
"<th scope='col'>Agreement with</th>"+
"<th scope='col'>Type of institution</th>"+
"<th scope='col'>Country</th>"+
/*Around 100+ Columns are there*/
"</thead>";
for(var i=0; i<dataArray.length; i++) {
result += "<tr>";
for(var j=0; j<dataArray[i].length; j++){
result += "<td>"+dataArray[i][j]+"</td>";
}
result += "</tr>";
}
result += "</table>";
var div = document.getElementById('search-results');
div.innerHTML = result;
}else{
var div = document.getElementById('search-results');
//div.empty()
div.innerHTML = "Data not found!";
}
}
</script>
<!--##JAVASCRIPT FUNCTIONS ~ END ---------------------------------------------------- -->
</head>
<body style="background-color:#cdffcd;">
<h1 align="center"><img src="https://drive.google.com/uc?export=download&id=16SqA92JMCD3AVWH07BeyPPLlEBaO_4Ae" alt="logo" width="120" height="100"/> The SoT Search Form</h1>
<div class="container">
<br>
<div class="row">
<div class="col">
<!-- ## SEARCH FORM ------------------------------------------------ -->
<form id="search-form" class="form-inline" onsubmit="handleFormSubmit(this)" action="/action_page.php" method="get">
<div class="form-group mb-2">
<label for="searchtext" align="center"><strong>Search for the provider</strong></label>
</div>
<div class="form-group mx-sm-3 mb-2">
<input id="searchtext" name="searchtext" class="form-control" onclick="myFunction()" placeholder="Enter the name.." align="center">
<!-- On keyup calls the function everytime a key is released -->
</div>
<button type="submit" class="btn btn-primary mb-2">Search</button>
<input type="reset" class="btn btn-primary mb-2" id="resetbutton" style='margin-left:16px' value="Reset">
</form>
<!-- ## SEARCH FORM ~ END ------------------------------------------- -->
</div>
</div>
<div class="row">
<div class="col">
<!-- ## TABLE OF SEARCH RESULTS ------------------------------------------------ -->
<div id="search-results" class="table-responsive">
<!-- The Data Table is inserted here by JavaScript -->
</div>
<!-- ## TABLE OF SEARCH RESULTS ~ END ------------------------------------------------ -->
</div>
</div>
</div>
</body>
</html>
============= Code File===========================================
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate();
}
/* PROCESS FORM */
function processForm(formObject){
var result = "";
if(formObject.searchtext){//Execute if form passes search text
result = search(formObject.searchtext);
}
return result;
}
//SEARCH FOR MATCHED CONTENTS
function search(searchtext){
var spreadsheetId = 'xxxxxxx';
var dataRage = 'ABC!A2:DV1500';
var data = Sheets.Spreadsheets.Values.get(spreadsheetId, dataRage).values;
var ar = [];
data.forEach(function(f) {
if (~f.indexOf(searchtext)) {
ar.push(f);
}
});
return ar;
}

Google Spread Sheet Search any part of the cell and display

I have a code to search and display the exact field in any column.
I would like to get the code of partial search, such that the input value if we entre is partial, should display all the possible fields.
Eg. Search "Evaluation" in the search field should display all the possible results.
enter image description here
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate();
}
/* PROCESS FORM */
function processForm(formObject){
var result = "";
if(formObject.searchtext){//Execute if form passes search text
result = search(formObject.searchtext);
}
return result;
}
//SEARCH FOR MATCHED CONTENTS
function search(searchtext){
var spreadsheetId = '1iG30kufq5MQpd0xmoPhPir5iA3hlz8s7vI_0EWQfg7Q'; //** CHANGE !!!
var dataRage = 'Data!A2:Y'; //** CHANGE !!!
var data = Sheets.Spreadsheets.Values.get(spreadsheetId, dataRage).values;
var ar = [];
data.forEach(function(f) {
if (~f.indexOf(searchtext)) {
ar.push(f);
}
});
return ar;
}
HTML CODE
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o" crossorigin="anonymous"></script>
<!--##JAVASCRIPT FUNCTIONS ---------------------------------------------------- -->
<script>
//PREVENT FORMS FROM SUBMITTING / PREVENT DEFAULT BEHAVIOUR
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, true);
//HANDLE FORM SUBMISSION
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(createTable).processForm(formObject);
document.getElementById("search-form").reset();
}
//CREATE THE DATA TABLE
function createTable(dataArray) {
if(dataArray && dataArray !== undefined && dataArray.length != 0){
var result = "<table class='table table-sm table-striped' id='dtable' style='font-size:0.8em'>"+
"<thead style='white-space: nowrap'>"+
"<tr>"+ //Change table headings to match witht he Google Sheet
"<th scope='col'>MS No</th>"+
"<th scope='col'>Title</th>"+
"<th scope='col'>Status</th>"+
"<th scope='col'>Date</th>"+
"</tr>"+
"</thead>";
for(var i=0; i<dataArray.length; i++) {
result += "<tr>";
for(var j=0; j<dataArray[i].length; j++){
result += "<td>"+dataArray[i][j]+"</td>";
}
result += "</tr>";
}
result += "</table>";
var div = document.getElementById('search-results');
div.innerHTML = result;
}else{
var div = document.getElementById('search-results');
//div.empty()
div.innerHTML = "Data not found!";
}
}
</script>
<!--##JAVASCRIPT FUNCTIONS ~ END ---------------------------------------------------- -->
</head>
<body>
<div class="container">
<br>
<div class="row">
<div class="col">
<!-- ## SEARCH FORM ------------------------------------------------ -->
<form id="search-form" class="form-inline" onsubmit="handleFormSubmit(this)">
<div class="form-group mb-2">
<label for="searchtext">Search MS No</label>
</div>
<div class="form-group mx-sm-3 mb-2">
<input type="text" class="form-control" id="searchtext" name="searchtext" placeholder="Enter MS No">
</div>
<button type="submit" class="btn btn-primary mb-2">Search</button>
</form>
<!-- ## SEARCH FORM ~ END ------------------------------------------- -->
</div>
</div>
<div class="row">
<div class="col">
<!-- ## TABLE OF SEARCH RESULTS ------------------------------------------------ -->
<div id="search-results" class="table-responsive">
<!-- The Data Table is inserted here by JavaScript -->
</div>
<!-- ## TABLE OF SEARCH RESULTS ~ END ------------------------------------------------ -->
</div>
</div>
</div>
<div class="container">
<br>
<div class="row">
<div class="col">
<!-- ## SEARCH FORM ------------------------------------------------ -->
<form id="search-form" class="form-inline" onsubmit="handleFormSubmit(this)">
<div class="form-group mb-2">
<label for="searchtext">Search Title</label>
</div>
<div class="form-group mx-sm-3 mb-2">
<input type="text" class="form-control" id="searchtext" name="searchtext" placeholder="Enter Title">
</div>
<button type="submit" class="btn btn-primary mb-2">Search</button>
</form>
<!-- ## SEARCH FORM ~ END ------------------------------------------- -->
</div>
</div>
<div class="row">
<div class="col">
<!-- ## TABLE OF SEARCH RESULTS ------------------------------------------------ -->
<div id="search-results" class="table-responsive">
<!-- The Data Table is inserted here by JavaScript -->
</div>
<!-- ## TABLE OF SEARCH RESULTS ~ END ------------------------------------------------ -->
</div>
</div>
</div>
</body>
</html>
This will highlight partial substring matches in red:
function searchhilight() {
let hilite = SpreadsheetApp.newTextStyle().setBold(true).setForegroundColor('red').build();
let normal = SpreadsheetApp.newTextStyle().setBold(false).setForegroundColor('black').build();
const ui = SpreadsheetApp.getUi();
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet0');
const sr = 2;//data start row
const rg = sh.getRange(sr, 1, sh.getLastRow() - sr + 1, sh.getLastColumn());
rg.setFontColor('black').setFontWeight('normal');//set all data to black text with no bold
const dvs = rg.getDisplayValues();
const resp = ui.prompt('Search Text', 'Enter Search String', ui.ButtonSet.OK_CANCEL);
if (resp.getSelectedButton() == ui.Button.OK) {
const st = resp.getResponseText();
dvs.forEach((r, i) => {
r.forEach((c, j) => {
let idx = '';
fidx = '';//from index
iA = [];//index array of matches
do {
idx = c.indexOf(st, fidx);
if (~idx) {
fidx = idx + st.length;
iA.push({ idxs: idx, idxe: idx + st.length })
}
} while (~idx);
let rtv = SpreadsheetApp.newRichTextValue().setText(c);
iA.forEach(obj => rtv.setTextStyle(obj.idxs, obj.idxe, hilite));
sh.getRange(i + sr, j + 1).setNumberFormat('#STRING#');
sh.getRange(i + sr, j + 1).setRichTextValue(rtv.build());
});
});
}
}
This function will also reformat every cell in the data range to plain text.
RichTextValueBuilder
RichTextValue
function search(searchtext){
var spreadsheetId = '1do6G8pScBAz0Z7GOCjbBcXPKJkhbOwlSx5BZyt6S7H8'; //** CHANGE !!!
var dataRage = 'Data!A2:Y'; //** CHANGE !!!
var data = Sheets.Spreadsheets.Values.get(spreadsheetId, dataRage).values;
var ar = [];
data.forEach(function(f) {
if (~f.toString().toLowerCase().indexOf(searchtext.toString().toLowerCase())) {
ar.push(f);
}
});
return ar;
}

Loading the arrays from server when DOMContentLoaded

I try to get the contents of 3 arrays from spreadsheet in 3 vars when the page is loaded in DOMContentLoaded. But I get nothing (look the picture)
I deployed the test project here: https://script.google.com/a/fmlogistic.com/macros/s/AKfycbxROleHY3u69jTpdVZjLOfDTzY9c5q1S4kwm0ctTFzU/dev
and test-spreadsheet with script of this is here
https://docs.google.com/spreadsheets/d/1qxr91eiLUykfLS0zKq3D4Dn206vnEkVqxDo6ZQF1rU4/edit#gid=0
I tried to write something like here, but this way with variantes Apps script return values from server function to html form
const inputs = document.querySelector('.dws-input');
const formControl = document.querySelectorAll('.form-control');
let findData;
let curInpID;
let firstValid, secValid, thirdValid, allValid;
formControl[0].focus();
function callBack(e) {
var Logs = e.ListLogins;
var Tabs = e.ListTables;
var Ords = e.ListOrders;
}
document.addEventListener("DOMContentLoaded", function(){
google.script.run.withSuccessHandler(callBack).sendData();
var Logs = e.ListLogins;
var Tabs = e.ListTables;
var Ords = e.ListOrders;
console.log(Logs);
console.log(Tabs);
console.log(Ords);
});
<!doctype html>
<html lang="en">
<head>
<title>CLR: PACKING</title>
<meta charset = "UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<link rel="stylesheet" href="https://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>
</head>
<body>
<div class="conteiner">
<form novalidate>
<h6 class="title">PACKING</h6>
<div class="dws-input">
<div class="col-md-3"></div>
<div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tLogin" name= "username" placeholder= "Login:" autofocus >
<label for="tLogin">Login:</label>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tTable" name= "text" placeholder= "Table:" >
<label for="tTable">Table:</label>
</div>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" novalidate class="form-control" id="tOrder" name= "text" placeholder= "Order:" >
<label for="tOrder">Order:</label>
</div>
</div>
</form>
</div>
<?!= include("index-js"); ?>
</body>
</html>
In actions.gs at server I wrote this:
const url = SpreadsheetApp.getActiveSpreadsheet().getUrl();
var htmlServ = HtmlService.createTemplateFromFile("index");
let ss = SpreadsheetApp.openByUrl(url);
let sheetTo = ss.getSheetByName("#sistem");
let sheetIn = ss.getSheetByName("#packing");
function doGet(e){
return htmlServ.evaluate();
}
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function sendData(){
var lrLogins = sheetTo.getRange("A:A").getValues().filter(String).length;
var arrLogins = sheetTo.getRange(1, 1, lrLogins, 1).getValues().flat();
var lrTMPLORDS = sheetTo.getRange("K:K").getValues().filter(String).length;
var curTMPLORDS = sheetTo.getRange(1, 11, lrTMPLORDS, 1).getValues();
var lrTABLES = sheetTo.getRange("R:R").getValues().filter(String).length;
var curTABLES = sheetTo.getRange(1, 18, lrTABLES, 1).getValues().flat();
var objDataInfo = {};
objDataInfo.ListLogins = arrLogins;
objDataInfo.ListTables = curTABLES;
objDataInfo.ListOrders = curTMPLORDS;
return objDataInfo;
}
Are there any ways to get the contents of these arrays when the page is loaded
Try this:
function callBack(e) {
var Logs = e.ListLogins;
var Tabs = e.ListTables;
var Ords = e.ListOrders;
console.log(Logs);
console.log(Tabs);
console.log(Ords);
}
document.addEventListener("DOMContentLoaded", function(){
google.script.run.withSuccessHandler(callBack).sendData();
//the following code is not in the callback function and it get's executed probably before the callback is returned.
var Logs = e.ListLogins;
var Tabs = e.ListTables;
var Ords = e.ListOrders;
console.log(Logs);
console.log(Tabs);
console.log(Ords);
});
It could have been written like this:
document.addEventListener("DOMContentLoaded", function () {
google.script.run.withSuccessHandler(function(e){
var Logs = e.ListLogins;
var Tabs = e.ListTables;
var Ords = e.ListOrders;
console.log(Logs);
console.log(Tabs);
console.log(Ords);
}).sendData();
});

How can I make a cell change colour every x seconds?

So I am working on a document on google sheets and I want it to look nice, this code really is unimportant but it would great to know how to do it, as every bit I learn anyways, can help in the future.
Something a bit more technical could be 1 cell changes to a certain colour, then the other cell identifies that that cell has changed colour so it also changes colour, and it keeps going until it loops on the last cell (to kind of create a rainbow effect).
Please remember though, a lot of conditional formatting is unavailable in google docs sheets and you can't use macros, you have to use Google Sheet Script.
Change color every x seconds
Code.gs:
function onOpen(){
SpreadsheetApp.getUi().createMenu('MyTools')
.addItem('Show Sidebar', 'showTimerSideBar')
.addToUi();
}
function showTimerSideBar()
{
var ui=HtmlService.createHtmlOutputFromFile('datatimer').setTitle('Color Timer');
SpreadsheetApp.getUi().showSidebar(ui);
}
function changeData(){
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('ColorChange');
var rg=sh.getRange('A1:A10');
var colorA=rg.getBackgrounds();
var n=new Date();
var tmr=Utilities.formatDate(n, Session.getScriptTimeZone(), "HH:mm:ss")
var rObj={color:colorA[Math.floor(Math.random()*colorA.length)][0],timer:tmr};
ss.toast(Utilities.formatString('timer: %s color: %s', rObj.timer,rObj.color));
return rObj;
}
function saveData(dObj) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Data');
var lr=sh.getLastRow();
sh.getRange(lr+1,1).setValue(dObj.timer);
sh.getRange(lr+1,2).setBackground(dObj.color);
}
function setA1(color) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('ColorChange');
var rg=sh.getRange('A1');
rg.setBackground(color);
}
datatimer.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
<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>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<style>
#my_block{border:2px solid black;background-color:rgba(0,150,255,0.2);padding:10px 10px 10px 10px;}
#conv_block{border: 1px solid black;padding:10px 10px 10px 10px;}
.bttn_block{padding:2px 5px 0px 0px;}
.sndr_block {border:1px solid rgba(0,150,0,0.5);background-color:rgba(150,150,0,0.2);margin-bottom:2px;}
</style>
</head>
<body>
<form>
<div id="my_block" class="block form-group">
<div class="sndr_block">
<div id="myClock" style="font-size:20px;font-weight:bold;"></div>
<br />Timer Duration(seconds):
<br /><input id="txt1" type="text" size="4" class="action"/>
<select id="sel1" onChange="loadTxt('sel1','txt1');">
</select>
<div id="cntdiv"></div>
<br /><strong>Timer Controls</strong>
<div class="bttn_block"><input type="button" value="Start" name="startShow" id="startShow" onClick="startmytimer();changeData();" class="red" /></div>
<div class="bttn_block"><input type="button" value="Stop" name="stopTimer" id="stopTimer" class="red" /></div>
<div class="bttn_block"><input type="button" value="Single Ping" name="changedata" id="chgData" class="red" onClick="changeData();" /></div>
<div class="bttn_block"><input type="button" value="Red" name="setA1Red" id="setRed" class="red" onClick="setA1('#ff0000');" /></div>
<div class="bttn_block"><input type="button" value="Green" name="setA1Green" id="setGreen" class="green" onClick="setA1('#00ff00');" /></div>
</div>
<div id="btn-bar">
<br /><input type="button" value="Exit" onClick="google.script.host.close();" class="green" />
</div>
</div>
</form>
<script>
var idx=1;
var myInterval='';
var cnt=0;
$(function() {
var select = document.getElementById('sel1');
select.options.length = 0;
for(var i=1;i<61;i++)
{
select.options[i-1] = new Option(i,i * 1000);
}
select.selectedIndex=4;
$('#startTimer').click(startmytimer);
$('#stopTimer').click(stopTimer);
$('#txt1').val(String(select.options[select.selectedIndex].value));
startTime();
});
function startTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('myClock').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i){
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
function startmytimer(){
document.getElementById('cntdiv').innerHTML='<strong>Timer Started:</strong> ' + document.getElementById('myClock').innerHTML;
myInterval=setInterval(changeData, Number($('#txt1').val()));
}
function stopTimer(){
document.getElementById('cntdiv').innerHTML='Timer Stopped';
clearInterval(myInterval);
}
function loadTxt(from,to){
document.getElementById(to).value = document.getElementById(from).value;
}
function exportData() {
google.script.run.saveData(cA);
}
function changeData(){
$('#txt1').css('background','#ffffcc');
google.script.run
.withSuccessHandler(function(rObj){
updateDisplay(rObj.timer);
saveData({timer:rObj.timer,color:rObj.color});
$('#txt1').css('background','#ffffff');
})
.changeData();
}
function updateDisplay(t){
$('#txt1').css('background','#ffffff');
document.getElementById('cntdiv').innerHTML='<strong>Timer Running:</strong> Count= ' + ++cnt + ' <strong>Time:</strong> ' + t;
}
function setA1(color) {
console.log(color);
google.script.run.setA1(color);
}
function saveData(dObj) {
google.script.run.saveData(dObj);
}
console.log('My Code');
</script>
</body>
</html>
Current Colors: (ColorChange Sheet)
Data Sheet:
Timer Sidebar:
I modified an existing script to provide you with this example. So there may be other unrelated scripts in here. Feel free to modify it to fit your specific needs.