How pass data between Google Spreadsheet Dialogs? - javascript

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

Related

Reorder CSV rows

I have this code which basically reads a CSV and should output a table where the CSV row content should be reordered!
Example :
fish;4;1;33
fish should be at 1 row column 4.
dog;5;2;66
dog should be at 2nd row column 5
The problem is that it doesn't print anything, neither at the console! Can you please show me where I am wrong? What modifications should I do?
My code:
function processFile() {
var fileSize = 0;
var theFile = document.getElementById("myFile").files[0];
if (theFile) {
var table = document.getElementById("myTable");
var headerLine = "";
var myReader = new FileReader();
myReader.onload = function(e) {
var content = myReader.result;
var lines = content.split("\r");
for (var i = 0; i <lines.length; i++)
{
document.write("<th>");
document.write(" ");
document.write("</th>");
}
for (var i = 0; i <lines.length; i++)
{
document.write("<tr>");
for (var j = 0; j <lines.length; j++)
{
document.write("<td>");
document.write(" ");
document.write("</td>");
}
document.write("</tr>");
}
function insertData(id, content) {
var dataRows = content.split("\r");
if (table) {
dataRows.forEach(function(s) {
var x = s.split(';');
table.rows[x[2]].cells[x[1]].textContent = x[0];
});
}
}
}
myReader.readAsText(theFile);
}
return false;
} //end
So, i did everything again for you with a big example.
I think you can handle it in your code, or take mine in the example.
Here are the main functions you can safely use in your case :
//for swapping values
function swap(arr, a, b){
var tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
return arr;
}
//for reorder lines a<=>b
function reorderLine(csvArray,a,b){
return swap(csvArray,a,b);
}
//for reorder one col values a<=>b
function reorderColumn(csvLine,a,b){
return swap(csvLine.split(";"),a,b).join(';');
}
// create a table with csv data
function csvArrayToTable(csvArray,selectorId){
var html = ["<table cellpadding='10' border='1'>"];
csvArray.map(function(lines){
html.push("<tr>");
var cols = lines.split(";");
html.push("<th>"+cols[0]+"</th>");
cols.shift();
cols.map(function(val){
html.push("<td>"+val+"</td>");
});
html.push("</tr>");
});
html.push("</table>");
document.getElementById(selectorId).innerHTML = html.join('');
}
And a working example you can use too, upload file is included (click on Run code snippet at the bottom of the post, and full page to test) :
//for swapping values
function swap(arr, a, b){
var tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
return arr;
}
//for reorder lines a<=>b
function reorderLine(csvArray,a,b){
console.log('reorderLine',csvArray,a,b);
return swap(csvArray,a,b);
}
//for reorder one col values a<=>b
function reorderColumn(csvLine,a,b){
console.log('reorderColumn',csvLine,a,b);
return swap(csvLine.split(";"),a,b).join(';');
}
// create a table with csv data
function csvArrayToTable(csvArray,selectorId){
var html = ["<table cellpadding='10' border='1'>"];
csvArray.map(function(lines){
html.push("<tr>");
var cols = lines.split(";");
html.push("<th>"+cols[0]+"</th>");
cols.shift();
cols.map(function(val){
html.push("<td>"+val+"</td>");
});
html.push("</tr>");
});
html.push("</table>");
document.getElementById(selectorId).innerHTML = html.join('');
}
// init element
var rawCsvFile = document.getElementById("csvInput");
var rawCsv = document.getElementById("rawCsv");
var reorderedRawCsv = document.getElementById("reorderedRawCsv");
var lines = document.getElementById("lines");
var lineA = document.getElementById("lineA");
var lineB = document.getElementById("lineB");
var colA = document.getElementById("colA");
var colB = document.getElementById("colB");
var apply = document.getElementById("apply");
var reset = document.getElementById("reset");
var rawCsvData, reorderCsvData;
// file uploaded
rawCsvFile.addEventListener("change", function() {
// reader
var reader = new FileReader();
// the file is loaded
reader.onload = function(e) {
// cancel if undefined
if(!reader.result || typeof reader.result != "string") return;
// Get result from new FileReader()
rawCsvData = reader.result.split(/[\r\n]+/g); // split lines
rawCsv.innerHTML = reader.result; // show in textarea
reorderedRawCsvData = rawCsvData; // clone data at start
function showCsvValueInForm(){
// empty fields
lines.innerHTML = "";
lineA.innerHTML = "";
lineB.innerHTML = "";
colA.innerHTML = "";
colB.innerHTML = "";
// Show in Raw CSV textarea
reorderedRawCsv.innerHTML = reorderedRawCsvData.join("\r\n");
// Add All option in On
var toAll = document.createElement('option');
toAll.value = "all";
toAll.innerHTML = "All";
lines.appendChild(toAll);
// handle line change
reorderedRawCsvData.map(function(val,i){
var lineOpt = document.createElement('option');
lineOpt.value = i;
lineOpt.innerHTML = i + " - " +(val.split(';'))[0];
// add options in line selects
lines.appendChild(lineOpt.cloneNode(!!1));
lineA.appendChild(lineOpt.cloneNode(!!1));
lineB.appendChild(lineOpt);
});
// handle col change
var nCol = rawCsvData[0].split(';');
nCol.map(function(val,i){
var colOpt = document.createElement('option');
colOpt.value = i;
colOpt.innerHTML = i;
// add options in col selects
colA.appendChild(colOpt.cloneNode(!!1));
colB.appendChild(colOpt);
});
// create table
csvArrayToTable(reorderedRawCsvData,"reorderedCsvTable");
}
// fill select, option and table with the reordered csv data
showCsvValueInForm();
// apply event, change the order
apply.addEventListener("click", function() {
// reordering line
var lineAOpt = lineA.options[lineA.selectedIndex].value;
var lineBOpt = lineB.options[lineB.selectedIndex].value;
if(lineAOpt !== lineBOpt) reorderedRawCsvData = reorderLine(reorderedRawCsvData,lineAOpt,lineBOpt);
// reordering col (all or only one)
var colAOpt = colA.options[colA.selectedIndex].value;
var colBOpt = colB.options[colB.selectedIndex].value;
if(colAOpt !== colBOpt)
if(lines.value == "all"){
reorderedRawCsvData = reorderedRawCsvData.map(function(val,i){
return reorderColumn(val,colAOpt,colBOpt);
});
}else{
reorderedRawCsvData[lines.value] = reorderColumn(reorderedRawCsvData[lines.value],colAOpt,colBOpt);
}
// fill again
showCsvValueInForm();
});
// reset the form with raw values
reset.addEventListener("click", function() {
if (confirm("Are you sure ?")) {
// reset
reorderedRawCsvData = rawCsvData;
// fill again
showCsvValueInForm();
}
});
}
// read the uploaded csv file as text
reader.readAsText(event.target.files[0], 'utf-8');
});
body { padding:10px; background:#eee; text-align: left; font-family: sans-serif; }
fieldset { width:80%; background:#fff; }
<html>
<head>
<title>CSV Reorder</title>
</head>
<body>
<h1>Reorder CSV</h1>
<fieldset>
<h3>Step 1 - Raw CSV</h3>
<small>Load a CSV file (not nested)</small>
<br />
<input type="file" id="csvInput">
<br />
<br />
<div>
<textarea id="rawCsv" placeholder="Waiting for a file..."></textarea>
</div>
</fieldset>
<br />
<fieldset>
<h3>Step 2 - Reordering Option</h3>
<small>Choose how to order the CSV data</small>
<br />
<table>
<tr>
<td>Line</td>
<td><select id="lineA"></select></td>
<td><=></td>
<td><select id="lineB"></select></td>
</tr>
<tr>
<td>Column</td>
<td><select id="colA"></select></td>
<td><=></td>
<td><select id="colB"></select></td>
<td>on</td>
<td><select id="lines"></select></td>
</tr>
<tr>
<td colspan="4"><button id="apply">Apply</button> <button id="reset">Reset</button></td>
</tr>
</table>
</fieldset>
<br />
<fieldset>
<h3>Step 3 - Reordered CSV</h3>
<small>Get the reordered values</small>
<br />
<div>
<textarea id="reorderedRawCsv" placeholder="Waiting for options..."></textarea>
</div>
<div>
<h3>Reordered CSV in a table</h3>
<div id="reorderedCsvTable">
<small>Waiting for a file..</small>
<br />
</div>
</div>
</fieldset>
</body>
</html>
Enjoy !

Getting blank screen after running Google web app script

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

how to add checkboxes in cells of first column of HTML table?

I am working on an app development which will read through my mailbox and list all the unread e-mails in a HTML table on my web-app upon click of a button. Below is the code which I have made while researching through google which solves for the purpose.
<!DOCTYPE html>
<html>
<body>
<button onclick="groupFunction()">Click me</button>
<table id="tblContents">
<tr onclick="tableClickTest()">
<th>Sender</th>
<th>Sent_Date</th>
<th>Received_By</th>
<th>Received_Date</th>
<th>Subject</th>
</tr>
</table>
<script>
function RowSelection()
{
var table = document.getElementById("tblContents");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
};
}
}
}
function tableText(tableCell) {
alert(tableCell.innerHTML);
}
function PopulateTable()
{
var objOutlook = new ActiveXObject("Outlook.Application");
var session = objOutlook.Session;
//alert(session.Folders.Count)
for(var folderCount = 1;folderCount <= session.Folders.Count; folderCount++)
{
var folder = session.Folders.Item(folderCount);
//alert(folder.Name)
if(folder.Name.indexOf("Premanshu.Basak#genpact.com")>=0)
{
for(var subFolCount = 1; subFolCount <= folder.Folders.Count; subFolCount++)
{
var sampleFolder = folder.Folders.Item(subFolCount);
//alert(sampleFolder.Name)
if(sampleFolder.Name.indexOf("test1")>=0)
{
for(var itmCount = 1; itmCount <= sampleFolder.Items.Count; itmCount++)
{
var itm = sampleFolder.Items.Item(itmCount);
if(!itm.UnRead)
continue;
var sentBy = itm.SenderName;
var sentDate = itm.SentOn;
var receivedBy = itm.ReceivedByName;
var receivedDate = itm.ReceivedTime;
var subject = itm.ConversationTopic;
// var contents = itm.Body;
var tbl = document.getElementById("tblContents");
if(tbl)
{
var tr = tbl.insertRow(tbl.rows.length);
// tr.onclick(tableClickTest())
if(tbl.rows.length%2 != 0)
tr.className = "alt";
var tdsentBy = tr.insertCell(0);
var tdsentDate = tr.insertCell(1);
var tdreceivedBy = tr.insertCell(2);
var tdreceivedDate = tr.insertCell(3);
var tdsubject = tr.insertCell(4);
// var tdcontents = tr.insertCell(5);
tdsentBy.innerHTML = sentBy;
tdsentDate.innerHTML = sentDate;
tdreceivedBy.innerHTML = receivedBy;
tdreceivedDate.innerHTML = receivedDate;
tdsubject.innerHTML = subject;
// tdcontents.innerHTML = contents;
}
//itm.UnRead = false;
}
break;
}
}
break;
}
}
return;
}
function groupFunction()
{
PopulateTable()
RowSelection()
}
</script>
</body>
</html>
The thing that I am now looking for and is unable to do is how do I add a checkbox in the first column in each row. Also upon checking this checkbox the entire row should get highlighted so that I can perform specific task on all the selected items.
As far as I have understood your code, your first column's data is being set as:
tdsentBy.innerHTML = sentBy;
So in the same line, you can add textbox as a string as:
var cbox = "<div class='select-box'>
<input type='checkbox' name='selectBox' class='select-row'>
</div?>"
tdsentBy.innerHTML = cbox + sentBy;
In this way, a checkbox will always be available in first column of every row.
Now in RowSelection function, to bind event you can do something like:
var checkBox = table.rows[i].cells[j].querySelector(".select-row");
checkBox.addEventListener("click",function(evt){
});

Refresh error loading local storage data

Sorry for being such a noob. I'm a student and I can't figure out what is wrong with my script. My code is a budget app where you enter values and it stores the info into local storage. It works when you calculate the expected and actual expenses, but when I refresh the page it adds a new row and with "undefined values". Any ideas?
<html>
<body onload="load()">
<div id="budget-list">
<ul>
<li>Expense Name</li>
<li>Expected Amount</li>
<li>Actual Amount</li>
</ul>
<div id="rowContent"></div>
<div id="output">
<input type="text" placeholder="Totals">
<input type="text" id="output-expected">
<input type="text" id="output-actual">
</div>
<button onclick="addRow()">Add New Row</button>
<input type="button" value="Save" onclick="save()" />
<input type="button" value="Add Expected" onclick="addExpectedTotals()" />
<input type="button" value="Add Actual" onclick="addActualTotals()" />
</div><!-- budget-list -->
</body>
</html>
<script>
/* BUDGET APP
******** 1. add a new set of rows
******** 2. enter data into input
******** 3. save data to local storage
******** 4. load data from local storage inside respective input id's
******** 5. calculate the total costs of expected/actual columns
*/
//a new line of rows
function addRow(){
var rowNumber = getCurrentCount();
var html = "<div class='rowClass'><input id='name-"+rowNumber+"' type='text'><input id='expected-"+rowNumber+"' type='text'><input id='actual-"+rowNumber+"' type='text'></div>";
var currentHtml = document.getElementById('rowContent').innerHTML;
document.getElementById('rowContent').innerHTML = currentHtml + html;
}
// count the number of divs under rowContent
function getCurrentCount(){
var parent = document.getElementById('rowContent');
return parent.getElementsByTagName('div').length;
}
// add the expected column totals
function addExpectedTotals(){
var rowNumber = getCurrentCount();
var all = new Array();
// loop for expected
for(i = 0; i < rowNumber; i++){
var expectedCol = document.getElementById("expected-" + [i]).value;
var theArray = all[i] = expectedCol;
var total = (eval(all.join(' + ')));
var stringTotal = JSON.stringify(total);
localStorage.setItem("ExpectedTotal", stringTotal);
localStorage.getItem(localStorage.key(stringTotal));
var parseTotal = JSON.parse(stringTotal);
var ouput = document.getElementById('output-expected').value = parseTotal;
}
}
// add the actual column totals
function addActualTotals(){
var rowNumber = getCurrentCount();
var actualArray = new Array();
// loop for actuals
for(i = 0; i < rowNumber; i++){
var actualCol = document.getElementById("actual-" + [i]).value;
var createArray = actualArray[i] = actualCol;
var addActual = (eval(actualArray.join(' + ')));
var stringActualTotal = JSON.stringify(addActual);
localStorage.setItem("ActualTotal", stringActualTotal);
localStorage.getItem(localStorage.key(stringActualTotal));
var parseActualTotal = JSON.parse(stringActualTotal);
var actualOutput = document.getElementById('output-actual').value = parseActualTotal;
}
}
// save the data
function save(){
var rowNumber = getCurrentCount();
// get the dynamic id for #name
for(var i = 0; i < rowNumber; i++){
var keyName = i;
var inputName = document.getElementById("name-" + [i]).value;
var inputExpected = document.getElementById("expected-" + [i]).value;
var inputActual = document.getElementById("actual-" + [i]).value;
var allIds = [inputName, inputExpected, inputActual];
var key_json = JSON.stringify(allIds);
localStorage.setItem("Item-" + i, key_json);
}
}
//load the data
function load(){
// add a new row for the data that is loaded
for(i = 0; i < localStorage.length; i++){
addRow();
}
// loop through the input fields and parse the data
for(i = 0; i < localStorage.length; i++){
var row = localStorage.getItem(localStorage.key(i));
var parsed = JSON.parse(row);
document.getElementById("name-" + i).value = parsed[0];
document.getElementById("expected-" + i).value = parsed[1];
document.getElementById("actual-" + i).value = parsed[2];
}
}
// initialize the app with a set of rows
document.addEventListener("DOMContentLoaded", function(event) {
addRow();
});

How do I delete a record in my javascript to do list?

I'm working on a to do list and I'm trying to create a delete button that will prompt an id number to delete a record. You pick which record you want to delete. Not sure how to go about doing it. This code has the html in it as well.
<!DOCTYPE html>
<html>
<head>
<title>To Do List</title>
<style>
body{margin:20px;}
</style>
<script type="text/javascript">
var list;
var addBtn;
document.addEventListener("DOMContentLoaded",load);
function load(){
list = get("list");
checkboxes = getTag("input");
addBtn = get("addBtn");
addBtn.addEventListener("click",addItem);
for(var i = 0, l = checkboxes.length; i < l ; i++){
if(checkboxes[i].type == "checkbox")
checkboxes[i].addEventListener("click",updatePercent);
}
if(localStorage.listFile)
//list.innerHTML = localStorage.listFile;
updatePercent();
}
function updatePercent(){
var checkboxes = getTag("input");
var total = checkboxes.length/2;
var done = 0;
for(var i = 0, l = checkboxes.length; i < l ; i++){
if(checkboxes[i].checked)
done++;
}
get("percentage").innerHTML = "Done: " + Math.round((done/total)*100) + "%";
}
function addItem(){
var item = document.createElement('li');
var chk = document.createElement("input");
var txt = document.createElement("input");
chk.type = "checkbox";
txt.type = "text";
chk.addEventListener("click",updatePercent);
item.appendChild(chk);
item.appendChild(txt);
list.appendChild(item);
updatePercent();
}
function get(id){
return document.getElementById(id);
}
function getTag(tag){
return document.getElementsByTagName(tag);
}
function save(){
localStorage.listFile = list.innerHTML;
}
function deleteTsk(){
var i = prompt("Enter number you want to delete") - 1;
//checkboxes[i].splice(i,1);
checkboxes[i].innerHTML = "";
}
</script>
</head>
<body>
<h1>Kung Fu To Do List 1.0</h1>
<ol id="list">
<li><input type="checkbox"><input type="text"></li>
</ol>
<p id="percentage"></p>
<button id="addBtn">Add Item</button><button onclick="save()">Save</button><button onclick="deleteTsk()">Delete</button>
</body>
I figured out how to delete it with this method.
function deleteTsk(){
var i = prompt("Enter number you want to delete") - 1;
var item = getTag("li");
list.removeChild(item[i]);
}
I figured out how to delete it with this method.
function deleteTsk(){
var i = prompt("Enter number you want to delete") - 1;
var item = getTag("li");
list.removeChild(item[i]);
}

Categories