How to convert CSV datas in <pre> into HTML table using Javascript? - javascript

I have a HTML file.
It has Pre-formatted text with CSV data in it.
<pre>1,2,3,4
5,6,7,8
9,0,1,2
3,4,5,6
</pre>
How to extract this data and convert it into a HTML table using Javascript?

If you know that the data is going to be in the exact format you gave, then something simple like this will work:
Markup:
<pre id="data">1,2,3,4
5,6,7,8
9,0,1,2
3,4,5,6</pre>
<div id="table"></div>
JavaScript:
var table = '';
var rows = new Array();
rows = document.getElementById('data').innerHTML.split('\n');
table += '<table>'
for(var i = 0; i < rows.length; i++) {
var columns = rows[i].split(',');
table += '<tr>';
for(var j = 0; j < columns.length; j++) {
table += '<td>' + columns[j] + '</td>';
}
table += '</tr>';
}
table += '</table>';
document.getElementById('table').innerHTML = table;
Demo

Use the function described in this answer. It returns an array if you give it CSV data. So given the data:
<pre id="CSV_DATA">1,2,3,4
5,6,7,8
9,0,1,2
3,4,5,6
</pre>
You can get the CSV into a Javascript string:
var csv_data = document.getElementById("CSV_DATA").innerHTML;
Then use the function CSVToArray to get an array of the data:
var array_data = CSVToArray(csv_data, ",");
Then make an HTML table:
var table=document.createElement('table');
table.border='1';
document.body.appendChild(table);
for(var i=0; i<array_data.length; i++){
var line = array_data[i];
var tr=document.createElement('tr');
for(var j=0; j<line.length; j++){
var td=document.createElement('td');
td.innerHTML = line[j];
tr.appendChild(td);
table.appendChild(tr);
}
}
I haven't tested this code. Please review it and work out the details. But what it's supposed to do is iterate through the array returned by CSVToArray and add each element of that array to a table row, then add each generated row to a table. The table is added to the document's body, but you can add it wherever you please.
And here's a demo of mine as well.

Related

Add a header row and a time column to a generated HTML table with jQuery

I have these two working JavaScript functions
https://github.com/cryptomanxxx/Random2DArrayPlusHtmlTable
https://cryptomanxxx.github.io/Random2DArrayPlusHtmlTable/
that 1) generates some random data 2) creates a HTML table for such data. There are two problems.
1) The HTML table column headings (the first row in the HTML table) are missing. Which is the simples way to add a row (should be the first row) with column headings to the HTML table? The column heading row should say something generic like this: variable 1, variable 2, variable 3 etc etc
2) The HTML table does not have a column with timestamps. A new column (first column) with timestamps would also be nice like: time 1, time 2, time 3 etc etc
It is obvious that I have not managed to understand how the code works because if I did it would be easy to modify the code. The complexity is overwhelming.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="JavaS.js"></script>
<meta charset="utf-8" />
<style>
table {
border-collapse: collapse;
}
table,
td,
th {
border: 1px solid black;
}
</style>
</head>
<body>
<div id="div1">
</body>
<script> htmlTable(RandomArray(8, 4)); </script>
</html>
function RandomArray(rows, cols) {
var arr = [];
for (var i = 0; i < rows; i++) {
arr.push([]);
arr[i].push(new Array(cols));
for (var j = 0; j < cols; j++) {
arr[i][j] = Math.random();
}
}
console.log(arr);
return arr;
}
function htmlTable(d) {
var data = d;
var html = '<table><thead><tr></tr></thead><tbody>';
for (var i = 0, len = data.length; i < len; ++i) {
html += '<tr>';
for (var j = 0, rowLen = data[i].length; j < rowLen; ++j) {
html += '<td>' + data[i][j] + '</td>';
}
html += "</tr>";
}
$(html).appendTo('#div1') ;
}
Don't stress about the complexity, it gets easier the longer you play with it.
1) If you want column headers, that's what th tags are for... and they should go inside the thead tags you already have, like this:
var html = '<table><thead><tr><th>Timestamp</th><th>Variable 1</th><th>Variable 2</th><th>Variable 3</th><th>Variable 4</th></tr></thead><tbody>';
Read more about HTML tables here.
2) If you want an additional column, add in a value (a td - short for table data) before the loop that adds the randomize values
...
html += '<tr>';
html += '<td>' + new Date().getTime() + '</td>' <------ NEW CODE TO ADD ANOTHER VALUE
for (var j = 0, rowLen = data[i].length; j < rowLen; ++j) {
...
You can learn more about dates, both creating them and displaying them, here.
All said and done, your function would look like:
function htmlTable(d) {
var data = d;
var html = '<table><thead><tr><th>Timestamp</th><th>Variable 1</th><th>Variable 2</th><th>Variable 3</th><th>Variable 4</th></tr></thead><tbody>';
for (var i = 0, len = data.length; i < len; ++i) {
html += '<tr>';
html += '<td>' + new Date().getTime() + '</td>'
for (var j = 0, rowLen = data[i].length; j < rowLen; ++j) {
html += '<td>' + data[i][j] + '</td>';
}
html += "</tr>";
}
$(html).appendTo('#div1') ;
}

Converting CSV input in textarea to dynamic table

This picture defines what I need
I want that the data I enter dynamically to be converted to table with each comma defining the column and the newline defining the new row.
Below is the code I have tried. Can I have a better approach to this problem?
<script>
function myFunction()
{
var x = document.getElementById("textarea").value.split(" ");
var customers = new Array();
customers.push(x[0]);
customers.push(x[1]);
customers.push(x[2]);
var table = document.createElement("TABLE");
table.border = "1";
//Get the count of columns.
var columnCount = customers[0].length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = customers[0][i];
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < customers.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < columnCount; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = customers[i][j];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
</script>
<html>
<head>
<title>Player Details</title>
</head>
<body align = "center">
<h3 align = "center"><b>Input CSV</b></h3>
<p align = "center"><textarea rows="10" cols="50" name = "csv" id = "textarea"></textarea></p><br>
<button type="button" id = "convert" onclick="myFunction()">Convert</button><br>
<br>
<div id = "team"></div>
</body>
</html>
You need to split the data first using newline (\n) and then using comma (,) character.
The table can be created as string and finally inserted to the correct div.
Refer the code below to get you started.
function myFunction() {
var tbl = "<table class='table table-responsive table-bordered table-striped'><tbody>"
var lines = document.getElementById("textarea").value.split("\n");
for (var i = 0; i < lines.length; i++) {
tbl = tbl + "<tr>"
var items = lines[i].split(",");
for (var j = 0; j < items.length; j++) {
tbl = tbl + "<td>" + items[j] + "</td>";
}
tbl = tbl + "</tr>";
}
tbl = tbl + "</tbody></table>";
var divTable = document.getElementById('team');
console.log(tbl);
divTable.innerHTML = tbl;
}
I've used bootstrap for css, you may want to use your own (or not).
Refer jsFiddle here.

Putting image in table using innerHTML (Javascript / Html)

Alright, some information right off the bat, I have a table that is dynamically being created.
The table looks roughly like this :
|item__ | price | category | category | category | category | picture |
|chicken| $20 | _______ |_ ______ | _______ | _______ | 1000.png|
var array = csvpls();
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++) {
if (j == 6) {
table += "<td>" + "<img src='CSV_Photos/" + array[i][j] +"'style ='width:500px;height:300px'>";
} else if {
table += "<td>" + array[i][j];
}
table += "<tr>";
table += "</tr>";
}
document.getElementById("Invtable").innerHTML = table;
This is the code that I have at the moment, where array is a 2D array. And every (6th column in the row, I want it to be an image) When runned, this does not display any table whatsoever.
In the code below
var array = csvpls();
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
for (var j = 0; j < array[i].length; j++) {
table += "<td>" + array[i][j];
}
table += "<tr>";
table += "</tr>";
}
document.getElementById("Invtable").innerHTML = table;
Without the if statement and the additional img content, the table displays perfectly, but obviously 1000.png shows up instead of the actual image.
CSV_Photos is a folder where the image is stored at, essentially in the same folder. I don't know what is wrong, any help or leads are appreciated.
Edit: So the 2nd part of the code I have works perfectly, It generates a table for me. But at every 6th column of a row is a picture name (1000.png) and its in the folder CSV_Photo. I want it to no display as 1000.png, but instead the picture. The 1st section of code is my attempt to make it an image, but no table is created so I'm guessing there is something wrong with this line table += "" + <"img src= 'CSV_Photos/" + array[i][j] +"'style ='width:500px;height:300px'>";
I think there are several problems in your code that needs to be fixed :
You are not appending the td elements inside the tr but directly
inside the table, you need to move the line table += "<tr>";
before the nested loop.
And you are not specifying closing tags for <td> elements so when
you include the img tag it will mess up the layout.
Another thing just inverse the use of " and ' in your img tag
definition because HTML uses ".." to define attributes.
Here's how should be your code:
var array = csvpls();
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
table += "<tr>";
for (var j = 0; j < array[i].length; j++) {
if (j == 6) {
table += "<td>" + '<img src="CSV_Photos/' + array[i][j] + '" style ="width:500px;height:300px"></td>';
} else if {
table += "<td>" + array[i][j] + "</td>";
}
}
table += "</tr>";
}
document.getElementById("Invtable").innerHTML = table;
Try:
var array = csvpls();
var table = "<table>";
for (var i = 0; i < array.length; i++) {
table += "<tr>";
for (var j = 0; j < array[i].length; j++) {
table += "<td>" + array[i][j];
}
table += "</tr>";
}
table += "</table>";
document.getElementById("Invtable").innerHTML = table;
If you wanted the image to be on the 2nd row, 3rd cell the condition should be:
if (i === 1 && j === 2) {...
If you want the whole 2nd row with the same image in each cell then it should be:
if (i === 1) {...
If you want a entire 3rd column to have the same image then it would be:
if (j === 2) {...
If it's a different image for every cell, then name each file by table coordinates like this...
img1-2.png
...then change the string that renders an image inside a cell as:
table += `<td><img src='http://imgh.us/img${i}-${j}.png' style ='width:50px;height:50px'></td>`
Or if I understand correctly, the array already has the filenames. If that's true, then the string should be...
table += `<td><img src='http://imgh.us/${array[i][j]}' style ='width:50px;height:50px'></td>`
... and the array would be something like this:
var array = [
['rt','AD','1000.png','uy','ii'],
['rt','AD','1001.png','uy','ii'],
['rt','AD','1002.png','uy','ii']
];
BTW, I had to do some changes to the code in order for it to work since it's only a partial code you provided, but the gist of it is the condition of course.
Also you'll notice the strange syntax of the strings, that's ES6 template literals or "strings on steroids".
Demo
var array = cvpls();
var table = ``;
for (var i = 0; i < array.length; i++) {
table += `<tr>`;
for (var j = 0; j < array[i].length; j++) {
if (i === 1 && j === 2) {
table += `<td><img src='http://imgh.us/statik.gif' style ='width:50px;height:50px'></td>`;
} else {
table += `<td>${array[i][j]}</td>`;
}
}
table += `</tr>`;
document.getElementById("Invtable").innerHTML = table;
}
function cvpls() {
return array = [
[4, 5, 6, 9, 2],
['img', 'img', 'img', 'img', 'img'],
['d', 'b', 'g', 'i', 'o']
];
}
td {
border: 1px solid black
}
<table id='Invtable'></table>

Assign Id and iterate through rows in Javascript

I created a table, which seems to work fine, but I have problems assigning an id to this table, count how many rows it has, and assign each row an id. The debugger says:
TypeError: document.getElementById(...) is null
I couldn't figure out what I did wrong. Can someone please help? I commented my questions in the code below as well:
function populateTable(list){
var tableContent = "<table>";
for (var i = 0; i < list.length; ++i) {
var record = list[i];
tableContent += "<tr><td>" + record.Title + "</td></tr>\n";
}
tableContent += "</table>";
tableContent.id="orders";
var rows = document.getElementById("orders").rows.length;//why is this null?
document.getElementById("test").innerHTML = rows;
for (var i=0; i< rows; ++i){
//how do I assign an id for the element here?
}
}
You can do this in this way:
HTML:
<div id="here"> </div> <!-- the table will be added in this div -->
JavaScript:
function populateTable(list){
var tableContent = document.createElement('table');
for (var i = 0; i < list.length; ++i) {
var record = list[i];
var cell = document.createElement('td');
var row = document.createElement('tr');
var textnode = document.createTextNode(record.Title);
cell.appendChild(textnode);
row.appendChild(cell);
tableContent.appendChild(row);
}
tableContent.id="orders";
document.getElementById("here").appendChild(tableContent); // the table is added to the HTML div element
var rows = document.getElementById("orders").rows;
for (var i=0; i < rows.length; ++i){
rows[i].id = "myId" + (i+1); // this is how you assign IDs
console.log(rows[i]);
}
}
var persons = [{Title:"John"}, {Title:"Marry"}];
populateTable(persons);
Edit
It seems you don't know how to properly create a DOM from javascript:
http://www.w3schools.com/jsref/met_document_createelement.asp
Old answer
This line:
var rows = document.getElementById("orders").rows.length;//why is this null?
Get elements from HTML document by id. And it looks like you have not added tableContent yet to the document.
Here's my suggestion (read the comments in the code):
// This will create a table element and return it
function createTable(list){
var table = document.createElement('table'); // This is an actual html element
table.id = 'orders'; // Since it's an html element, we can assign an id to it
tableHtml = ''; // This empty string will hold the inner html of the table we just created
for (var i = 0; i < list.length; ++i) {
var record = list[i];
// we can assign the id here instead of looping through the rows again
tableHtml += '<tr id="row-' + i + '"><td>' + record.Title + '</td></tr>';
}
table.innerHTML = tableHtml; // We insert the html into the table element and parse it
var rows = table.rows.length; // We already have a reference to the table, so no need of getElementById
alert('rows'); // rows holds the number of rows. You can do whatever you want with this var.
return table; // return the table. We still need to insert it into the dom
}
// Create a new table and hold it in memory
var myTable = createTable([{Title:'One'}, {Title:'Two'}, {Title:'Three'}]);
// Inset the newly created table into the DOM
document.getElementById('parent-of-table').appendChild(myTable);
Hope this helps
This is already been answered, but here's my version without all the comments:
function createTable(list){
var table = document.createElement('table');
table.id = 'orders';
tableHtml = '';
for (var i = 0; i < list.length; ++i) {
tableHtml += '<tr id="row-' + i + '"><td>' + list[i].Title + '</td></tr>';
}
table.innerHTML = tableHtml;
var rows = table.rows.length;
alert('rows');
return table;
}

Appending Xml Data to List View JQuery Mobile

I am unable Show Parsed Response from Xml Service in JQuery Mobile List View. I unable to get were the Problem is,what i have Tried is.
First i took all the Response to theXML var then iam Trying to append to ListView Which i have Dynamically Created in javaScript Code. Here is my Code,
function processXML(theXML) {
var nodeTree = theXML.documentElement.getElementsByTagName('Employee');
var output = "";
output += "<ul data-role='listview' class='ui-listview'>";
var length = nodeTree.length;
for (var i = 0; i < length; i++) {
var empName = nodeTree[i].getElementsByTagName('name')[0].firstChild.nodeValue;
var empFName = nodeTree[i].getElementsByTagName('Fathername')[0].firstChild.nodeValue;
var empAddr = nodeTree[i].getElementsByTagName('Address')[0].firstChild.nodeValue;
output += buildRow(empName, empFName, empAddr);
}
output += "</ul>";
document.getElementById('result').innerHTML = output;
}
function buildRow(empName, empFName, empAddr) {
var row = "<li><a href='#'>";
row += empName;
row += empFName;
row += empAddr;
row += "</a></li>";
return row;
}
$("result").html(output).trigger("create");
$(".ui-listview").listview('refresh')‌​;

Categories

Resources