How To Convert CSV file to HTML table - javascript

i have csv file with the content :
heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2
I create Javascript/HTML code to pick up that file and display the content
<html>
<head>
<title>show csv</title>
</head>
<body>
<input type="file" id="fileinput" multiple />
<div id="result"></div>
<script type="text/javascript">
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (files) {
for (var i=0, f; f=files[i]; i++) {
var r = new FileReader();
r.onload = (function(f) {
return function(e) {
var contents = e.target.result;
var res = document.getElementById("result");
res.innerHTML = "Got the file<br>"
+"name: " + f.name + "<br>"
+"type: " + f.type + "<br>"
+"size: " + f.size + " bytes</br>"
+ "starts with: " + contents;
};
})(f);
r.readAsText(f);
}
} else {
alert("Failed to load files");
}
}
document.getElementById('fileinput').addEventListener('change',readMultipleFiles, false);
</script>
</body>
</html>
and the output is like :
output
question : How can i convert the content or the data to array and showing as html table ?
thanks for any help.

You can convert csv data into array and then into html table. I have added \n into your new line. Please add the \n to your code when there is a new line.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
table {
border-collapse: collapse;
border: 2px black solid;
font: 12px sans-serif;
}
td {
border: 1px black solid;
padding: 5px;
}
</style>
</head>
<body>
<div id='container'></div>
<script type="text/javascript"charset="utf-8">
var data = 'heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2';
var lines = data.split("\n"),
output = [],
i;
for (i = 0; i < lines.length; i++)
output.push("<tr><td>"
+ lines[i].slice(0,-1).split(",").join("</td><td>")
+ "</td></tr>");
output = "<table>" + output.join("") + "</table>";
var div = document.getElementById('container');
div.innerHTML = output;
</script>
</body>
</html>

I found Kapila Perera's answer to be very useful. However, the last element of each row was being cropped due to the slice(0,-1) use. Building on Perera's answer, in the example below I've used slice() instead.
I've also separated out the first row lines[0] as a header row and loop from 1 instead (which won't always be the case that csv contains headers but is explicitly called out in the example).
Finally, I've added the tbody tags when the output gets wrapped but this probably isn't required.
<script type="text/javascript"charset="utf-8">
var div = document.getElementById('container');
var data = 'heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2';
var lines = data.split("\n"), output = [], i;
/* HEADERS */
output.push("<tr><th>"
+ lines[0].slice().split(",").join("</th><th>")
+ "</th></tr>");
for (i = 1; i < lines.length; i++)
output.push("<tr><td>"
+ lines[i].slice().split(",").join("</td><td>")
+ "</td></tr>");
output = "<table><tbody>"
+ output.join("") + "</tbody></table>";
div.innerHTML = output;
</script>

Related

Copying file names from upload to textarea

I have a code that will copy the file names and add them to the textarea. Everything works but when you add more files, the first ones are deleted. How to fix it?
updateList = function() {
var input = document.getElementById('file');
var output = document.getElementById('fileList');
output.innerHTML = '';
for (var i = 0; i < input.files.length; ++i) {
output.innerHTML += '\n' + input.files.item(i).name + '';
}
output.innerHTML += ' \n';
}
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Display file name in page after selecting file in file input</title>
</head>
<form>
<input type="file" name="file" id="file" multiple
onchange="javascript:updateList()" />
<br/>Selected files:
<textarea id="fileList"></textarea>
<script src="js/index.js"></script>
</body>
</html>
FIDDLE: https://jsfiddle.net/yhw8zfue/
You are setting your textarea value to empty string.
You can fix by removing the line:
output.innerHTML = '';
When you add more files the function will run again and updste your filelist. but in your code you reset the list of files here:
output.innerHTML = '';
so instead you want to have whats currently in there. replace it with that:
updateList = function() {
var input = document.getElementById('file');
var output = document.getElementById('fileList');
output.innerHTML = output.value;
for (var i = 0; i < input.files.length; ++i) {
output.innerHTML += '\n' + input.files.item(i).name + '';
}
output.innerHTML += ' \n';
}

How to multiply XML values in an XML table?

XML table (as rendered in Firefox 47.0.1)
The .XML file doesn't contain nodes for Total Price, but I can still derive it in the XML table by multiplying PRICE * QUANTITY.
I am aware of this solution:
y[i].getElementsByTagName("PRICE")[0].childNodes[0].nodeValue * y[i].getElementsByTagName("QUANTITY")[0].childNodes[0].nodeValue
However I would like to multiply variables instead:
p * q
So I have already declared variables for PRICE and QUANTITY (p and q):
var p = y[i].getElementsByTagName("PRICE")[0].childNodes[0].nodeValue
var q = y[i].getElementsByTagName("QUANTITY")[0].childNodes[0].nodeValue
But this only yields the correct result for the first row (Unit 1).
Why is this not working?
Here's my example.xml
<?xml version="1.0" encoding="UTF-8"?>
<CUSTOMER_ORDER>
<UNIT>
<NAME>Unit 1</NAME>
<QUANTITY>45</QUANTITY>
<PRICE>25.99</PRICE>
</UNIT>
<UNIT>
<NAME>Unit 2</NAME>
<QUANTITY>209</QUANTITY>
<PRICE>9.95</PRICE>
</UNIT>
<UNIT>
<NAME>Unit 3</NAME>
<QUANTITY>80</QUANTITY>
<PRICE>14.99</PRICE>
</UNIT>
<UNIT>
<NAME>Unit 4</NAME>
<QUANTITY>156</QUANTITY>
<PRICE>35.88</PRICE>
</UNIT>
<UNIT>
<NAME>Unit 5</NAME>
<QUANTITY>25</QUANTITY>
<PRICE>199.00</PRICE>
</UNIT>
</CUSTOMER_ORDER>
Here's my test html
<!DOCTYPE html>
<html>
<style>
table,
th,
td {
border: 2px solid black;
border-collapse: collapse;
}
th,
td {
padding: 5px;
}
</style>
<body>
<body onload="loadXMLDoc()">
<table id="test"></table>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
testFunction(xmlhttp);
}
};
xmlhttp.open("GET", "example.xml", true);
xmlhttp.send();
}
function testFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Unit</th><th>Price</th><th>Quantity</th><th>Total Price</th></tr>";
var y = xmlDoc.getElementsByTagName("UNIT");
for (i = 0; i > y.length; i++);
var p = y[i].getElementsByTagName("PRICE")[0].childNodes[0].nodeValue;
var q = y[i].getElementsByTagName("QUANTITY")[0].childNodes[0].nodeValue;
for (i = 0; i < y.length; i++)
{
table += "<tr><td>" +
y[i].getElementsByTagName("NAME")[0].childNodes[0].nodeValue +
"</td><td>" +
y[i].getElementsByTagName("PRICE")[0].childNodes[0].nodeValue +
"</td><td>" +
y[i].getElementsByTagName("QUANTITY")[0].childNodes[0].nodeValue +
"</td><td>" +
p * q + // This is the total price column yielding 1169.55 across all rows.
"</td></tr>";
}
document.getElementById("test").innerHTML = table;
}
</script>
</body>
</html>
The problem turned out to be syntax and the solution is very simple. Thanks to everyone who contributed their input.
You can see the final testfunction(xml) here:
function testFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Unit</th><th>Price</th><th>Quantity</th><th>Total Price</th></tr>";
var y = xmlDoc.getElementsByTagName("UNIT");
for (i = 0; i < y.length; i++)
{
var p = y[i].getElementsByTagName("PRICE")[0].childNodes[0].nodeValue;
var q = y[i].getElementsByTagName("QUANTITY")[0].childNodes[0].nodeValue;
var n = y[i].getElementsByTagName("NAME")[0].childNodes[0].nodeValue;
table += "<tr><td>" +
n +
"</td><td>" +
p +
"</td><td>" +
q +
"</td><td>" +
p*q + // This is the total price column.
"</td></tr>";
}
document.getElementById("test").innerHTML = table;
}

Cannot read property 'childNodes' of undefined when trying to retrieve data from an XML file

Given this code,
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<form>
<input type="text" id="word" value=""/>
<button type="button" onclick="loadDoc()">Retrieve data</button>
<br>
</form>
<br><br>
<table id="demo"></table>
<script type="text/javascript">// <![CDATA[
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
xhttp.open("GET", "URL" + $('#word').val(), true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Japanese</th><th>Pronunciation</th><th>English</th></tr>";
var x = xmlDoc.getElementsByTagName("json");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("japanese")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("pronunciation")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("english")[0].childNodes[0].nodeValue +
"</td>" + " " + "</tr>";
}
document.getElementById("demo").innerHTML = table;
}
// ]]></script>
How could I skip the "pronunciation" tag whenever it has no value?
To be a little more specific, my XML file has different tags - "japanese" (a word or kanji), "pronunciation" (how the word is read, in hiragana, and only has a value when it's a kanji) and "english" (meaning of the word).
The current code does not work whenever a value is missing for the "pronunciation" tag, which means that every single word without a pronunciation will cause the site not to display anything.
XML File:
<json> //This entry has pronunciation
<japanese>原爆</japanese>
<pos>n</pos>
<pronunciation>げんばく</pronunciation>
<english>(abbr) (See 原子爆弾) atomic bomb A-bomb</english>
</json>
<json> //This entry does not have pronunciation as it is not needed
<japanese>ダム</japanese>
<pos>n</pos>
<english>dam/(adj-f)</english>
<english>dumb</english>
</json>
Thanks!
From your sample data, the pronunciation element is completely omitted when not needed. So getElementsByTagName("pronunciation") returns undefined, and because of that, you can't get [0] from it.
You can test what comes back and respond appropriately, like this:
var pron = getElementsByTagName("pronunciation");
if (pron) { table += pron[0].childNodes[0].nodeValue; }
This assumes you split the one long assignment to 'table', into separate parts. In general, you may find it useful to factor this out into a function like:
function getOptionalContentAsTD(ename) {
var el = getElementsByTagName(ename);
var txt = "";
if (el) { txt = el[0].childNodes[0].nodeValue; }
return("<td>" + txt + "</td>");
}
I didn't test this, so there's probably a typo, but it's gives the idea.
Hope that helps.

Creating a div using JavaScript/Dom and a textarea

I have this code and it isn't working the way i want. I want it to create a new div under the other one everytime the button is clicked, but it is just changing the content of the div. help
<!DOCTYPE html>
<html>
<head>
<style>
p{
background-color: red;
font-family: arial;
}
</style>
</head>
<body>
Name: <textarea id="myText" value=""></textarea>
<button type="button" onclick="myFunction()">Enviar</button>
<div id="demo"></div>
<script>
function myFunction() {
var x = document.getElementById("myText");
var defaultVal = x.defaultValue;
var textoComentario = x.value;
if (defaultVal == textoComentario) {
alert("Digite um comentário!");
} else {
document.getElementById("demo").innerHTML = "<p>" + textoComentario + "</p>";
x.value = "";
}
}
</script>
</body>
</html>
You can try with jquery more easily:
$('<div/>').html(textoComentario).appendTo('#demo');
EDIT
You can make it with pure-javascript with createElement too:
http://www.w3schools.com/jsref/met_document_createelement.asp
Good luck!
I think you are looking for this:
WORKING:DEMO
HTML
NO CHANGE
CSS
NO CHANGE
JS/JQuery
function myFunction() {
var x = document.getElementById("myText");
var defaultVal = x.defaultValue;
var textoComentario = x.value;
alert(textoComentario);
if (defaultVal == textoComentario) {
alert("Digite um comentário!");
} else {
$("#demo").css("display","block");
$("#demo").append("<p>" + textoComentario + "</p>");
x.value = "";
}
}
Replace your
document.getElementById("demo").innerHTML = "<p>" + textoComentario + "</p>";
into $('#demo').append("<p>" + textoComentario + "</p>");
It will work.......

Create HTML table with hyperlink from JSON Object

I have an application which returns a JSONObject. I am able to get data from JSON object using below code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<head>
<style type="text/css">
table, td, th
{
border:1px collapse black;
font-family:Arial;
font-size :small;
}
th
{
background-color:green;
color:white;
}
.hideMe
{
/*display : none;*/
/*visibility: hidden;*/
}
</style>
<script type="text/javascript" language="jscript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js">
</script>
<script type="text/javascript" language="javascript">
var host = "somehost";
var mystr = "http://"+ host +"/rest/bpm/wle/v1/exposed/process"; // use get for this
var ulink = "";
$(document).ready(function () {
$.get(mystr, function (data) {
var obj = JSON.parse(data);
var thtml = "<table id='proctable'>";
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "<tr><td><a onclick='my_function()' href='javascript:void(0)'>" + obj.data.exposedItemsList[i].display + "</a></td><td id='linkcell' class='hideMe'>" + ulink + "</td></tr>";
}
thtml = thtml + "</table>";
document.getElementById('contentdiv').innerHTML = thtml;
});
});
//javascript
my_function = null;
//jquery
$(function () {
function generateBPDInstance() {
$.post(ulink, function (taskdata) {
var tobj = JSON.parse(taskdata);
alert(tobj.data.tasks[0].name);
alert(tobj.data.tasks[0].tkiid);
});
}
my_function = generateBPDInstance;
ulink = "";
})
`
</script>
</head>
<body>
<form name="myform">
<div id="contentdiv">
<table id="proctable">
</table>
</div>
</form>
</body>
</html>
The above html creates a table showing a list of the returned values. I also want to get rowIndex of hyperlink and pass value of column2 to function generateBPDInstance.
I am not so good at HTML and Jquery. Please suggest how can I get rowIndex for HTML table which is created through javascript.
Thanks in advance.
The simple way is :
change your table building to this
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "" + obj.data.exposedItemsList[i].display + "" + ulink + "";
function my_function(e){
//e is the row index and when you call document.getLementById("proctable").rows[e]; this will give you the complete row.
}
--this is a simple way, and if you want traverse the tree and get , you always have parentnode or you can use jquery $(object).parent() to get the parent of hyperlink and traverse.
You problem is "pass value of column2 to function generateBPDInstance". Why not pass it already while generating the table?
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "<tr><td><a onclick='my_function('" + ulink + "')' href='javascript:void(0)'>" + obj.data.exposedItemsList[i].display + "</a></td><td id='linkcell' class='hideMe'>" + ulink + "</td></tr>";
// ------------------------------------------------------^ pass the value
}
Add parameter to your function generateBPDInstance
function generateBPDInstance(ulink) {
//--------------------------^----
$.post(ulink, function (taskdata) {
var tobj = JSON.parse(taskdata);
alert(tobj.data.tasks[0].name);
alert(tobj.data.tasks[0].tkiid);
});
}

Categories