I wish to display sum of amount for particular region.
Below is my code to display the data, however I am sure how to add up the amount.
I am able to read csv file an display in html table.
I am new to Javascript. Any help to proceed would be much appreciated
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function loadFile(o)
{
var fr = new FileReader();
fr.onload = function(e)
{
showDataFile(e, o);
};
fr.readAsText(o.files[0]);
}
function showDataFile(e, o)
{
var getCSVData = e.target.result;
var rows = getCSVData.split("\n");
var html = '<table border="1">';
rows.forEach((data, index) =>
{
html += "<tr>";
var value = data.split(",");
var region = value[1];
var amount =value[3];
if(region=="SA")
{
html += "<td>" + region + "</td>";
html += "<td>" + amount + "</td>"
}
html += "</tr>";
});
html += '</table>';
document.getElementById("data").innerHTML = html;
document.getElementById("data").style.color="blue";
}
</script>
<title> Read CSV file using JavaScript </title>
</head>
<body>
Select file to read <input type="file" onchange="loadFile(this)">
<pre id="data"></pre>
</body>
</html>
You need to create a variable that you use as an accumulator to save the result of the sum, for example:
var sum = 0;
for (i = 1; i <= 10; i++) {
sum += 10;
}
console.log(sum)
Following your idea, you need to create a variable initialized at 0 before forEach and then inside the loop, accumulate its result
NOTE:
1. When you read your .csv file, it is received as a String, so the value of the variable amount is also a String, so before making the sum it should be transformed to a Number type to avoid concatenate
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)
Solution:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function loadFile(o)
{
var fr = new FileReader();
fr.onload = function(e)
{
showDataFile(e, o);
};
fr.readAsText(o.files[0]);
}
function showDataFile(e, o)
{
var getCSVData = e.target.result;
var rows = getCSVData.split("\n");
var html = '<table border="1">';
var sum = 0;
rows.forEach((data, index) =>
{
html += "<tr>";
var value = data.split(",");
var region = value[1];
var amount = value[3];
if(region=="SA")
{
if (Number(amount)) {
sum += Number(amount)
}
html += "<td>" + region + "</td>";
html += "<td>" + amount + "</td>"
}
html += "</tr>";
});
html += '</table>';
html += '<span>' + sum + '</span>';
document.getElementById("data").innerHTML = html;
document.getElementById("data").style.color="blue";
}
</script>
<title> Read CSV file using JavaScript </title>
</head>
<body>
Select file to read <input type="file" onchange="loadFile(this)">
<pre id="data"></pre>
</body>
</html>
Related
I making a table and show it in the modal dialogue so that buttons will appear for each row in the table. My question is how to make the button in the modal dialogue run for specific row in spreadsheet? Example : click first button in first row in modal dialogue, will run and change data in first row of spreadsheet. Do I need to create specific ID for each buttons?
My GS code:
function leadRespond(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Query_Script");
var dataRange = sheet.getDataRange();
var dataValue = dataRange.getDisplayValues();
var temp = HtmlService.createTemplateFromFile("lead");
temp.data = {application : dataValue};
var html = temp.evaluate().setWidth(1200).setHeight(600);
SpreadsheetApp.getUi().showModalDialog(html,"Manage Leave");
}
HTML code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Leave Application</h1>
<div id="output"></div>
<script>
var output = document.getElementById("output");
window.onload = function (){
google.script.run.withSuccessHandler(onSuccess).getTable();
}
function onSuccess(data){
if(data.success){
console.log(data.data);
var html = '<table>';
var row;
for(var i=0; i<data.data.length; i++){
html += '<tr>';
row = i;
//console.log(row);
for (var j=0; j<9; j++){
html += '<td>'+ data.data[i][j]+'</td>';
}
html += '<td>'+ '<button onclick="approve()">Approved</button>'+'</td>';
html += '</tr>';
}
html += '</table>';
output.innerHTML = html;
console.log(data);
}
}
function approve(){
google.script.run.getRow();
console.log("test");
}
</script>
</body>
</html>
Code with google.script.run :
function getTable(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Query_Script");
var data = sheet.getDataRange().getDisplayValues();
Logger.log(data);
return {'success': true,'data':data};
}
function getRow(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Query_Script");
for (var i=0; i<dataValue.length; i++){
var row = "";
var rowNum;
for (var j = 0; j < 9; j++) {
if (dataValue[i][j]) {
row = row + dataValue[i][j]; //row = "" + range(0,0) [emailAddress], row = range(0,0)+ range(0,1)[emailAddress,Timestamp]
}
row = row + ",";
}
row = row + " Row num " + i;
rowNum = i;
Logger.log(row);
Logger.log(rowNum);
}
}
Use custom html-data attributes and delegate event to <table>:
html += '<td>'+ '<button data-row="'+i+'" data-column="'+j+'">Approved</button>'+'</td>';
//...
output.innerHTML = html;
console.log(data);
const table = document.querySelector("table");
table.addEventListener('click', approve);
}
function approve(e){
const td = e.target;
const [row, column] = [td.dataset.row,td.dataset.column];
google.script.run.modifyRows(row,column);
}
So as a beginner, I have no idea how to create a table using Javascript. I can make a table using a simple html file but not in Javascript.
The output should have 2 columns and 4 rows. I also need to use the prompt tag in order to insert data for the second column. Not to mention that I need to average the total number in the 2nd column.
I tried searching but I got mixed results and its confusing me.so please help me
this is the html file
<html>
<body>
<table border="1" style="width:30%">
<tr>
<td>Rose</td>
<td>40</td>
</tr>
<tr>
<td>Daisy</td>
<td>50</td>
</tr>
<tr>
<td>Orchids</td>
<td>60</td>
</tr>
<tr>
<td>Flowers</td>
<td>150</td>
</tr>
</table>
</body>
</html>
Try this - >
var Rose = prompt("Enter price for Rose?");
var Daisy = prompt("Enter price for Daisy?");
var Orchids = prompt("Enter price for Orchids?");
var flowers = Number(Rose) + Number(Daisy) + Number(Orchids);
var table = document.createElement("table");
createTable();
function createTable(){
createTrTds("Rose",Rose);
createTrTds("Daisy",Daisy);
createTrTds("Orchids",Orchids);
createTrTds("Total",flowers);
document.getElementById("table").appendChild(table);
}
function createTrTds(text,value){
var tr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var txt1 = document.createTextNode(text);
var txt2 = document.createTextNode(value);
td1.appendChild(txt1);
td2.appendChild(txt2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
td
{
border: 1px solid black;
}
<div id="table">
</div>
You will be helped by using a framework for this, jquery or angularjs comes to mind to solve it. However the pure JavaScript way looks like this:
This will create a table with inputs for the number of flowers and sum them up at the bottom when numbers change, you can also add more flower types in the JavaScript file.
var tabledef = [];
tabledef['Rose'] = 40;
tabledef['Daisy'] = 50;
tabledef['Orchids'] = 60;
writeTable();
function writeTable() {
var table = '<table border="1" style="width:30%">';
var sum = 0;
for (var i in tabledef) {
sum = sum + tabledef[i];
table = table + '<tr><td>' + i + '</td><td><input id="' + i + '" onchange="recalculate(this)" type="number" value="' + tabledef[i] + '"></td></tr>';
}
table = table + '<tr><td>Flowers</td><td>' + sum + '</td></tr></table>';
document.getElementById('myTable').innerHTML = table;
}
function recalculate(box) {
tabledef[box.id] = box.valueAsNumber;
writeTable();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="myTable"></div>
<script src="createTable.js"></script>
</body>
</html>
You just need array with data and then fill table as thought it was an html document
var table = '<table border="1">',
data = [['Rose','Daisy','Orchids','Flowers'],[40,50,60,150]];
for (var i = 0; i < data[0].length; i++) {
table += '<tr>';
for (var j = 0; j < data.length; j++) {
table += '<td>' + data[j][i] + '</td>';
}
table += '</tr>';
}
table += '</table>';
document.getElementById('container').innerHTML = table;
http://jsfiddle.net/5pdac6sb/
I'm taking in a csv file, which includes the test value 'Iñtërnâtiônàlizætiøn' and outputting it to a simple HTML table using JavaScript.
The table displays the output as I�t�rn�ti�n�liz�ti�n. I've been looking on the web and have tried the suggestions of changing font & also charset (tried UTF-8, UTF-16, windows-1252, iso 8859-1 & iso 8859-5) but nothing works.
It's a drag and drop that takes in the csv and changes it into an HTML table on the webpage and uses xml to output a word document of the same table.
Sorry, I should have said:- There is no PHP on this page, it all takes place in the local browser, hence JavaScript. Also, I don't have control over the coding of the files being used or the settings in the user's browser. Most of my users are going to be making this file in excel, I suspect.
Here is the code:
<div id="drop_zone">Drop files here</div>
<output id="list"></output>
<script type="text/javascript" >
var URLadd = "My url here";
var OutString = [];
var TestFunc = [];
function handleFileSelect(evt) { // function 1 bracket
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files; // FileList object.
// files is a FileList of File objects. List some properties.
var output = [];
oForm = document.forms[0];
oText = oForm.elements["Inst"];
var InstCode = oText.value;
if (InstCode == "")
{
InstCode = "<b>Please enter your institution code</b>";
}
for (var i = 0, f; f = files[i]; i++) { // loop 1
if (f.name.match('\.csv')) { // if 1
// this part is for when a csv file is drag n dropped
var Filename = decodeURI(escape(f.name));
var reader = new FileReader();
// when the file loads, the function beneath is run
reader.onload = (function(theFile) { // function 2
// this function is executed before it is returned, by the last parenthesis (f)
return function(e) { //function 3
var contents = e.target.result;
var FileLines = contents.split( "\n" );
var LineCount = FileLines.length;
OutString = '<table id="mytab" border="1" width="100%"><tr>';
var ColCount = 1;
for (var i=1; i<LineCount; ++i)
{ // loop 2
if (ColCount>4)
{ColCount=0;}
if(ColCount==0)
{ // if 2
OutString += '</tr><tr>';
ColCount = 1;
} // close if 2
OutString += '<td width=25%>';
var CommaSplit = FileLines[i].split(",");
var CommaCount = CommaSplit.length;
if (CommaCount == 5)
{ // if 3
OutString += "<strong> " + CommaSplit[0] + " " + CommaSplit[1] + "</strong><br>";
OutString += "Username: " + CommaSplit[3] + "<br>Password: " + CommaSplit[3];
OutString += "<br>Institution Code: " + InstCode + "<br>" + URLadd;
ColCount += 1;
} else { // else of if 3
for (var j= 0; j<CommaCount; ++j)
{ // loop 3
OutString += CommaSplit[j] + '<br>';
ColCount += 1;
} // close loop 3
} //close if 3
OutString += '</td>';
} // close loop 2
OutString += '</tr></table>';
TestFunc = '<html xmlns:v="urn:schemas-microsoft-com:vml" ';
TestFunc += 'xmlns:o="urn:schemas-microsoft-com:office:office" ';
TestFunc += 'xmlns:w="urn:schemas-microsoft-com:office:word" ';
TestFunc += 'xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" ';
TestFunc += 'xmlns="http://www.w3.org/TR/REC-html40">';
TestFunc += '<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta><title>Passwords Doc</title>';
TestFunc += '<style>v\:* {behavior:url(#default#VML);}o\:* {behavior:url(#default#VML);}w\:* {behavior:url(#default#VML);}.shape behavior:url(#default#VML);}</style>';
TestFunc += '<style>#page{mso-page-orientation: landscape; size:29.7cm 21cm; margin:0cm 0cm 0cm 0cm;}';
TestFunc += '#page Section1 {mso-header-margin:0in; mso-footer-margin:0in; mso-header: h1; mso-footer: f1; }';
TestFunc += ' div.Section1 { page:Section1; }';
TestFunc += 'table#mytab{ margin: 0.2in 0.2in 0.2in 0.2in; width:0px; height:0px; overflow:hidden;}';
TestFunc += '</style><xml><w:WordDocument><w:View>Print</w:View><w:Zoom>100</w:Zoom><w:DoNotOptimizeForBrowser/>';
TestFunc += '</w:WordDocument></xml></head><body><div class="Section1">';
TestFunc += OutString;
TestFunc += '</div></body></html>';
var OutPutLine = "<a href='data:application/msword;charset=UTF-8, " + encodeURIComponent(TestFunc) + "' download='" + decodeURIComponent(escape('Login Slips.doc')) + "' ><input id='Button1' type='button' value='Open printable sheet' /></a>";
output.push(OutPutLine);
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
var span = document.createElement('span');
span.innerHTML = [OutString].join('');
document.getElementById('list').insertBefore(span, null);
}; // close function 3
})(f); // close function 2
reader.readAsText(f);
// this creates the button that opens the finished document
//var OutPutLine = "<a href='WordTemplate.doc' ><input id='Button1' type='button' value='Open printable sheet' /></a>";
output.push(OutPutLine);
} else { // else of if 1
// this triggers if its not a csv file that drag n drops
output.push('<strong>', escape(f.name), ' is not a comma seperated (.csv) file!!!!</strong>');
} // close if 1
} // close loop 1
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
} // close function 1
function handleDragOver(evt) { // function 4
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
} // close function 4
// Setup the dnd listeners.
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
</script>
I'm very new to both JQuery and Javascript. I have an feed, I would like to display these feed inside a collapsible div AS a collapsible div. I have the following Javascript file:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("feeds", "1");
google.setOnLoadCallback(showFeed);
function showFeed() {
var feed = new google.feeds.Feed("http://www.varzesh3.com/rss");
feed.setNumEntries(10);
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("headlines");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var di = document.createElement("div").setAttributeNode("data-role", "collapsible");
di.innerHTML = '<h3>' + entry.title + '</h3>';
di.innerHTML += '<p>' + entry.contentSnippet + '</p>';
container.appendChild(di);
}
} else {
var container = document.getElementById("headlines");
container.innerHTML = '<li>Get your geek news fix at site</li>';
}
});
}
</script>
<body>
<div data-role="collapsible-set" id="headlines"></div>
</body>
This should fetch all my feed names and put them in a collapsible div, it does exactly that but it shows the names as plain HTML text instead of a JQuery Mobile collapsible div.
#AML, that is more a comment than an answer because a don't analyse your entire code, but I will put here for formatting purposes.
In the line:
var di = document.createElement("div").setAttributeNode("data-role", "collapsible");
You don't take a pointer(di) to the new created element, you take a result of the setAttributeNode(...), You need to split the code in two lines like that:
var di = document.createElement("div");
di.setAttribute("data-role", "collapsible");
There are a problem with setAttributeNode actually is setAttribute.
Now is working, see at http://pannonicaquartet.com/test/feeds.html
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
.collapsible{
display : none;
}
h3{
background-color : lightgray;
}
</style>
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load("feeds", "1");
function showFeed() {
var feed = new google.feeds.Feed("http://www.varzesh3.com/rss");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("headlines");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.onclick = function(evt){
var elP = this.children[1];
if(elP.style.display == 'inline'){
elP.style.display = 'none';
}else{
elP.style.display = 'inline';
}
};
div.innerHTML = '<h3>' + entry.title + '</h3>';
div.innerHTML += '<p class="collapsible">' + entry.contentSnippet + '</p>';
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(showFeed);
</script>
I am trying to get tweets from different zip codes.For doing this, I am using latitude and longitude values for each zip code. So far I want to get 3 tweets for each zip code(I have 2 zip codes), but it is working only for one zip code.
Any suggestion will be appreciated. Thank you in advance!
Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
var lat=[41.9716,42.0411];
var lng=[-87.7026,-87.6900];
$(document).ready(function() {
for(var i=1; i<2; i++)
{
$.getJSON('http://search.twitter.com/search.json?q=business&geocode='+lat[i]+','+lng[i]+',5mi&lang=en&callback=?', function(data) {
var data = data.results;
var html = "";
for(var j=0; j<3;j++){
html += "<div style='width:600px;border:solid thin blue'><img src='"+data[j].profile_image_url+"'/><a href='http://twitter.com/" + data[j].from_user + "'>#"+ data[j].from_user + "</a>: " + data[j].text + "</div>";
}
$('.content'+i).html(html);
}); }
});
</script>
</head>
<body>
<div class="content1"></div>
<div class="content2"></div>
</body>
I found 2 problems with your code:
1) If you want to iterate 2 times, your for function should be like this: for (var i = 0; i < 2; i++)
2) You must have in consideration that the function that gets called in $.getJSON runs asynchronously, so when that function gets called the for will have already finished, therefore you can't use the i value with that purpose inside that function.
So, after correcting those 2 things in your code you should be able to get what you want. Try with something like this:
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
var lat = [41.9716, 42.0411];
var lng = [-87.7026, -87.6900];
var count = 1;
$(document).ready(function () {
for (var i = 0; i < 2; i++) {
$.getJSON('http://search.twitter.com/search.json?q=business&geocode=' + lat[i] + ',' + lng[i] + ',5mi&lang=en&callback=?', function (data) {
var data = data.results;
var html = "";
for (var j = 0; j < 3; j++) {
html += "<div style='width:600px;border:solid thin blue'><img src='" + data[j].profile_image_url + "'/><a href='http://twitter.com/" + data[j].from_user + "'>#" + data[j].from_user + "</a>: " + data[j].text + "</div>";
}
$('.content' + count++).html(html);
});
}
});
</script>
</head>
<body>
<div class="content1"></div>
<div class="content2"></div>
</body>
</html>