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 !
Related
Here, there is an example to show contents of one upload file.
.js
$scope.uploadFilename = function (files) {
if (!files[0]) {
return;
}
var reader = new FileReader();
reader.onload = function (e) {
var str = reader.result;
var csv = str.split(/\n/);
var headers = csv[0].split(',');
var str_result = '';
for (var i = 1; i < csv.length - 1; i++) {
var curline = csv[i].split(',');
var tmp = '' + curline[1];
if (i == csv.length - 2) {
str_result += tmp.split('"').join('');
} else {
str_result += tmp.split('"').join('') + '\n';
}
}
angular.element('#upload_keywords_list').val(str_result);
$scope.uploadedKeywordsCount = csv.length - 2;
};
reader.readAsText(files[0]);
};
.html
<div class="chosefile">
<div class="clearfix">
<input type="file" name="file" class="pull-left" onchange="angular.element(this).scope().uploadFilename(this.files)">
<textarea id="upload_keywords_list" class="form-control" rows="10"></textarea>
<div class="uploaded-keywords-count" ng-if="uploadedKeywordsCount > 0">
<strong>Total number: </strong>{{ uploadedKeywordsCount }}
</div>
</div>
</div>
I want to show contents of multi upload files.
Can you tell me the method how to do it?
And then, how to change the value of total number, when i edit the contents of textarea that I've already opened?
Thanks.
Hope this works.
I removed uploaded-keywords-count and textarea from your html. And added a new div
<div id="textAreaContainer"></div>
Also i made changes to your script. I wrapped your code inside for loop
Now, you can select multiple files, at once or one by one it doesn't matter.
And if you try to select the same file again, it warns you. and rejects the file again.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="fileApp" ng-controller="myCtrl">
<script>
var app = angular.module('fileApp', []);
app.controller('myCtrl', function($scope) {
var allFiles = [];
$scope.uploadFilename = function (files) {
if (!files[0]) {
return;
}
cnt = files.length;
for (var k = 0; k < cnt; k++) {
if(!allFiles.includes(files[k].name)) {
var reader = new FileReader();
reader.fileName = files[k].name;
allFiles.push(reader.fileName);
reader.onload = function (e) {
var str = e.target.result;
var csv = str.split(/\n/);
var headers = csv[0].split(',');
var str_result = '';
for (var i = 1; i < csv.length - 1; i++) {
var curline = csv[i].split(',');
var tmp = '' + curline[1];
if (i == csv.length - 2) {
str_result += tmp.split('"').join('');
} else {
str_result += tmp.split('"').join('') + '\n';
}
}
$scope.uploadedKeywordsCount = csv.length - 2;
var containerData = "";
containerData += '<div id="fileContent' + k + '"><textarea>' + str_result + '</textarea>';
containerData += '<span>' + $scope.uploadedKeywordsCount + '</span></div>'
var containerHtml = $(containerData);
angular.element('#textAreaContainer').append(containerHtml);
};
reader.readAsText(files[k]);
//console.log(files[k]);
} else {
alert('File already exists');
}
}
}
});
$(document).on('keyup', 'textarea', function(){
$(this).closest("div").find('span').html($(this).val().split(/\n/).length);
})
</script>
<div class="chosefile">
<div class="clearfix">
<input type="file" name="file" class="pull-left" onchange="angular.element(this).scope().uploadFilename(this.files)" multiple>
<div id="textAreaContainer"></div>
</div>
</div>
</div>
I forgot to tell you that i added a new script for your second question. Now you can edit the textarea, and the lines count changes.
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.
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){
});
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();
});
I'm trying to create a table in HTML using javascript. It has an add button that add's new rows and a delete button that removes rows. It looks like this :
the numbers are the ids
<table id = "table1" border = 2>
<tr>
<td> <img id="add" src="images/add_over.png" onclick=help() /> </td>
</tr>
</table>
Basically I'm trying to delete the whole table and recreate it with one row less.
var array1 = new Array();
function help() {
addRow();
push();
}
function addRow() {
var tableId= "table1";
var number= array1.length;
var newRow = document.getElementById(tableId).insertRow(number+ 1);
var newData = document.createElement("td");
var newDiv= document.createElement("div");
newDiv.innerHTML = array1.length;
newData.appendChild(newDiv);
var newCellDeleteButton = document.createElement("td");
var deleteButtonImg = document.createElement('img');
deleteButtonImg.id = number;
deleteButtonImg.border = '0';
deleteButtonImg.src = "images/delete_up.png";
deleteButtonImg.onmouseover = function() {
this.src = 'images/delete_over.png';
};
deleteButtonImg.onmouseout = function() {
this.src = 'images/delete_up.png';
};
deleteButtonImg.onclick = function() {
deleteRow(number);
};
newCellDeleteButton.appendChild(deleteButtonImg);
newRow.appendChild(newRow);
newRow.appendChild(newCellDeleteButton);
}
function deleteRow(rowID) {
var tempHelpRow = array1.length;
pop(rowID);
for (var i = 1; i <= tempHelpRow ; i++) {
document.getElementById("table1").deleteRow(1);
}
for (var i = 0; i <= array1.length; i++) {
addRow();
}
}
function pop(ID) {
array1.pop(ID);
}
function push() {
var test = new objectt();
array1.push(test);
}
function objectt() {
}
the problem is, that if i try to delete one row it deletes everything.