Refresh error loading local storage data - javascript

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();
});

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 !

Storing inputed numerical values with a for loop on JavaScript/HTML

I am new to JavaScript and am trying to program this code for my school. The ultimate goal is to make a final grade calculator where the students input their current grades and the program outputs what they need to score on the final to keep a certain percentage. This program is supposed to be for weighted classes in which the teachers weight different assignments/tests different amounts. The problem is that some teachers use more categories than others which is why there is a for loop. With the following, the user is able to input all the info but I cannot store the extra category weights and grades as a variable so I cant do the math with them. If that made any sense, I would appreciate if you knew how to store the values that are inputed within the for loops.
<html>
<head>
<script type='text/javascript'>
function addFields() {
// Number of inputs to create
var number = document.getElementById("category_weight").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++){
// create a row element to contain each pair
var row = document.createElement("div");
row.id = 'row' + i
row.appendChild(document.createTextNode("Category " + (i+1) + " weight: "));
var weight_input = document.createElement("input");
weight_input.type = "number";
weight_input.name = "weight";
row.appendChild(weight_input);
row.appendChild(document.createTextNode("Category " + (i+1) + " percentage: "));
var percentage_input = document.createElement("input");
percentage_input.type = "number";
percentage_input.name = "percentage";
row.appendChild(percentage_input);
// append inputs to row instead of container, then append each row to container
container.appendChild(row);
}
}
function weighted() {
var container = document.getElementById("container");
var rows = container.children;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var weight = row.children[0].value; // or row.querySelectorAll('[name=weight]').value;
var percentage = row.children[1].value;
console.log(weight, percentage);
}
// not important for now - will do the calculations here
// var E = "";
//
// var A = parseFloat(document.getElementById("goal_grade").value);
// var B = parseFloat(document.getElementById("exam_weight").value);
//
//
// var E = A + B;
//
// if ( E <= 0) {
// E = 0;
// }
//
//
// document.getElementById("result").innerHTML = E;
// document.getElementById("totpoints").innerHTML = B;
}
</script>
</head
<body>
<span>What final percentage in the class are you trying to reach or stay above?</span>
<input type="number" id="goal_grade" name="goal_grade" />
<br>
<br>
<span>What percent is the final exam weighted?</span>
<input type="number" id="exam_weight" name="exam_weight" />
<br>
<br>
<span>How many extra weighted categories are there?</span>
<input type="number" id="category_weight" name="category_weight" value=""> <br />
<button type="button" onclick="addFields()">Submit </button>
<div id="container"></div>
<br>
<br>
<input type="button" value="Calculate" onclick="weighted()" />
<br>
<br>
<span>You will need to get <p id="result" name="r1"> </p> points out of the ... <p id="totpoints" name="tot_points"> </p> points possible on the final"
</span>
</body>
</html>
Just use array in javascript. I have used array and your page is working fine now.
You can check it and Tell if there some problem...
<html>
<head>
<script type='text/javascript'>
var w = [];
var p = [];
var result = 0;
function addFields() {
// Number of inputs to create
var number = document.getElementById("category_weight").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++){
// create a row element to contain each pair
var row = document.createElement("div");
row.id = 'row' + i
row.appendChild(document.createTextNode("Category " + (i+1) + " weight: "));
var weight_input = document.createElement("input");
weight_input.type = "number";
weight_input.name = "weight";
row.appendChild(weight_input);
row.appendChild(document.createTextNode("Category " + (i+1) + " percentage: "));
var percentage_input = document.createElement("input");
percentage_input.type = "number";
percentage_input.name = "percentage";
row.appendChild(percentage_input);
// append inputs to row instead of container, then append each row to container
container.appendChild(row);
}
}
function weighted() {
var container = document.getElementById("container");
var rows = container.children;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
w[i] = row.children[0].value; // or row.querySelectorAll('[name=weight]').value;
p[i] = row.children[1].value;
}
for(var i =0; i < rows.length; i++){
// You can do as much calculation here with w[i] & p[i]
result += w[i]*p[i];
}
console.log(result);
// not important for now - will do the calculations here
// var E = "";
//
// var A = parseFloat(document.getElementById("goal_grade").value);
// var B = parseFloat(document.getElementById("exam_weight").value);
//
//
// var E = A + B;
//
// if ( E <= 0) {
// E = 0;
// }
//
//
// document.getElementById("result").innerHTML = E;
// document.getElementById("totpoints").innerHTML = B;
}
</script>
</head
<body>
<span>What final percentage in the class are you trying to reach or stay above?</span>
<input type="number" id="goal_grade" name="goal_grade" />
<br>
<br>
<span>What percent is the final exam weighted?</span>
<input type="number" id="exam_weight" name="exam_weight" />
<br>
<br>
<span>How many extra weighted categories are there?</span>
<input type="number" id="category_weight" name="category_weight" value=""> <br />
<button type="button" onclick="addFields()">Submit </button>
<div id="container"></div>
<br>
<br>
<input type="button" value="Calculate" onclick="weighted()" />
<br>
<br>
<span>You will need to get <p id="result" name="r1"> </p> points out of the ... <p id="totpoints" name="tot_points"> </p> points possible on the final"
</span>
</body>
</html>
I hope this will solve your problem :)
Didn't quite understand where your problem is. You can store all of your extra weighted categories inside of an array.
for example:
var categories = [];
categories.push(value);
For your issue, value can be a weighted category (weight + percentage).
Your code should be as follows:
<html>
<head>
<script type='text/javascript'>
function addFields() {
// Number of inputs to create
var number = document.getElementById("category_weight").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++){
// create a row element to contain each pair
var row = document.createElement("div");
row.id = 'row' + i
row.appendChild(document.createTextNode("Category " + (i+1) + " weight: "));
var weight_input = document.createElement("input");
weight_input.type = "number";
weight_input.name = "weight";
row.appendChild(weight_input);
row.appendChild(document.createTextNode("Category " + (i+1) + " percentage: "));
var percentage_input = document.createElement("input");
percentage_input.type = "number";
percentage_input.name = "percentage";
row.appendChild(percentage_input);
// append inputs to row instead of container, then append each row to container
container.appendChild(row);
}
}
function weighted() {
var container = document.getElementById("container");
var rows = container.children;
// The categories array initialization
var categories = [];
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var weight = row.children[0].value; // or row.querySelectorAll('[name=weight]').value;
var percentage = row.children[1].value;
// Pushing a specific category that contains weight and percentage (Defined by a JSON struction)
categories.push({
weight: weight,
percentage: percentage
});
console.log(weight, percentage);
}
// not important for now - will do the calculations here
// var E = "";
//
// var A = parseFloat(document.getElementById("goal_grade").value);
// var B = parseFloat(document.getElementById("exam_weight").value);
//
//
// var E = A + B;
//
// if ( E <= 0) {
// E = 0;
// }
//
//
// document.getElementById("result").innerHTML = E;
// document.getElementById("totpoints").innerHTML = B;
}
</script>
</head
<body>
<span>What final percentage in the class are you trying to reach or stay above?</span>
<input type="number" id="goal_grade" name="goal_grade" />
<br>
<br>
<span>What percent is the final exam weighted?</span>
<input type="number" id="exam_weight" name="exam_weight" />
<br>
<br>
<span>How many extra weighted categories are there?</span>
<input type="number" id="category_weight" name="category_weight" value=""> <br />
<button type="button" onclick="addFields()">Submit </button>
<div id="container"></div>
<br>
<br>
<input type="button" value="Calculate" onclick="weighted()" />
<br>
<br>
<span>You will need to get <p id="result" name="r1"> </p> points out of the ... <p id="totpoints" name="tot_points"> </p> points possible on the final"
</span>
</body>
</html>
Later on your calculations, your can for loop on the categories array and calculate by the categories that you've pushed into the array

How pass data between Google Spreadsheet Dialogs?

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.

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){
});

how to display the previous user input along with the new input

I am new to Html and I am trying to create a script to display user input back to the user.whenever i am entering a new input,the new user input over rides the previous input. but i need to display all the user inputs? how to do it using Javascript.
my code
<html><head></head><body>
<input id="title" type="text" >
<input type="submit" value="Save/Show" onclick="clearAndShow()" />
<div id="display2letter"></div>
<div id="display3letter"></div>
<div id="display4letter"></div>
<script type="text/javascript">
var titleInput = document.getElementById("title");
var display2letter = document.getElementById("display2letter");
var display3letter = document.getElementById("display3letter");
var display4letter = document.getElementById("display4letter");
function clearAndShow () {
// Split input box value by comma
titles = titleInput.value.split(",");
// Reset display divs
display2letter.innerHTML = "";
display3letter.innerHTML = "";
display4letter.innerHTML = "";
// Cache length so it's not recalculated on each iteration.
var len = titles.length;
var twoletter = [];
var threeletter = [];
var fourletter =[];
for (i = 0; i < len; i++) {
// Check for a-z, A-Z,
if (!titles[i].match(/^[a-zA-Z]/)) {
throw error("Please use only alphabet letters");
}
// Dump into storage arrays.
if(titles[i].length == 2) {
twoletter.push(titles[i]);
}
else if(titles[i].length == 3){
threeletter.push(titles[i]);
}
else if(titles[i].length == 4){
fourletter.push(titles[i]);
}
}
display2letter.innerHTML += " 2 letters: " + twoletter.join(", ") + "<br/>";
display3letter.innerHTML += " 3 letters: " + threeletter.join(", ") + "<br/>";
display4letter.innerHTML += " 4 letters: " + fourletter.join(", ") + "<br/>";
}
</script>
</body>
</html>
Try declaring these variables -
var twoletter = [];
var threeletter = [];
var fourletter =[];
before the clearAndShow () function, ie,
<script type="text/javascript">
var titleInput = document.getElementById("title");
var display2letter = document.getElementById("display2letter");
var display3letter = document.getElementById("display3letter");
var display4letter = document.getElementById("display4letter");
var twoletter = [];
var threeletter = [];
var fourletter =[];
function clearAndShow () {

Categories