How to display multiple CSV files as separate tables using javascript? - javascript

I am currently using the script below to display CSV data in a HTML table.
function createDataElement(htmlTag, innerText, idParent) {
let node = document.createElement(htmlTag);
let textnode = document.createTextNode(innerText);
node.appendChild(textnode);
document.getElementById(idParent).appendChild(node);
}
function createHeaderElement(columnText) {
createDataElement("th", columnText, "tableHeader");
}
function createCellData(rowIndex, dataIndex, cellText) {
if (dataIndex === 0) {
let node = document.createElement("tr");
node.setAttribute("id", "row" + rowIndex);
document.getElementById("tableBody").appendChild(node);
createDataElement("td", cellText, "row" + rowIndex);
} else {
createDataElement("td", cellText, "row" + rowIndex);
}
}
var csv_url = 'https://www.sample-videos.com/csv/Sample-Spreadsheet-10-rows.csv';
Papa.parse(csv_url, {
download: true,
complete: function(results) {
for (let i = 0; i < results.data.length; i++) {
if (i === 0) {
for (let j = 0; j < results.data[i].length; j++) {
createHeaderElement(results.data[i][j]);
}
}
if (i > 0) {
for (let j = 0; j < results.data[i].length; j++) {
createCellData(i, j, results.data[i][j]);
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.3.1/papaparse.min.js"
integrity="sha512-EbdJQSugx0nVWrtyK3JdQQ/03mS3Q1UiAhRtErbwl1YL/+e2hZdlIcSURxxh7WXHTzn83sjlh2rysACoJGfb6g=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<table style="width: 90vw; margin: auto;" class="table table-sm table-striped">
<thead>
<tr id="tableHeader">
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
However, this only works for one HTML table. I have tried adding unique classes to the table but it will still only show one.
How do I adapt this code to show multiple tables from seperate CSV files?
<thead> and <tbody> are required as I am styling with Bootstrap.
Cannot loop through the different CSV files as there is content between each table, so need to be able to position the HTML tables separately.
Need to be able to add a unique class to the <table> for additional styling.

Related

Adding data from json into html table using javascript

I am trying to build a table, where first cell is an image , next cells have some values, for which header is defined in thead.
The issue is that, in javascript, for every iteration of loop, it adds a new row, though I have not used <tr>
fetch("./static/js/data.json")
.then(response => response.json())
.then(data => {
for (var j = 0; j < 10; j++) {
let imgsrc = data.data[j].image;
document.querySelector("#userdata").innerHTML +=
`<tr><td rowspan="8"><img src=${imgsrc} width="150" height="150"></td>`;
for (var i = 0; i < 5; i++) {
let vmovieID = data.data[j].ingredients[i].contents;
document.querySelector("#userdata").innerHTML += `<td>${vmovieID}</td>`;
}
}
document.querySelector("#userdata").innerHTML += '</tr>'
});
<div class="panel-body">
<table id="userdata">
<thead>
<th>Image</th>
<th>Dry Matter</th>
<th>CP</th>
<th>GE</th>
<th>Calcium</th>
</thead>
</table>
</div>
Results are:
It's recommended to use Javascript to create and append the elements as variables, rather than appending strings of HTML at various points.
Additionally, you should confirm the DOM is loaded before targeting elements to avoid any bugs.
Refactored code with the points from above:
<script>
const fetchedData = fetch("./static/js/data.json");
window.addEventListener("DOMContentLoaded", (event) => {
fetchedData
.then((response) => response.json())
.then((data) => {
const table = document.getElementById("userdata");
for (var j = 0; j < 10; j++) {
const imgsrc = data.data[j].image;
const row = document.createElement("tr");
row.innerHTML = `<td rowspan="8"><img src=${imgsrc} width="150" height="150"></td>`;
for (var i = 0; i < 5; i++) {
const vmovieID = data.data[j].ingredients[i].contents;
const textContent = document.createTextNode(vmovieID);
const cell = document.createElement("td");
cell.appendChild(textContent);
row.appendChild(cell);
}
table.appendChild(row);
}
})
.catch((error) => {
console.error(new Error(error));
});
});
</script>
<div class="panel-body">
<table id="userdata">
<thead>
<th>Image</th>
<th>Dry Matter</th>
<th>CP</th>
<th>GE</th>
<th>Calcium</th>
</thead>
</table>
</div>

I want to create a html table layout in jQuery

I am trying to create an Html table layout using jQuery but I don't know where I am doing mistakes.
When I try to run this and check the console tab the error comes with undefined( i and table2)
I just want to show the table on the chrome page means I want the output.
$(document).ready(function() {
function table() {
this.column = col;
}
function col(value1, value2) {
var multiply = (value1 * value2);
return multiply;
}
var table2 = new table();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Table Layout</h1>
<table border="solid 3px" style="font-size: 20px;" width="100%">
<thead>
<tr>
<script>
for (var j = 1; j <= 10; j++) {
console.log("<th><label'>" + i + "</label></th>");
}
</script>
</tr>
</thead>
<tbody>
<script>
for (var i = 1; i <= 5; i++) {
console.log("<tr>");
for (var k = 1; k <= 5; k++) {
var value1 = i;
var value2 = k;
console.log("<td>" + table2.column(value1, value2) + "</td>");
}
console.log("</tr>");
}
</script>
</tbody>
</table>
This should do it.
There was an i inside but it should be an j
console.log("<th><label'>" + j + "</label></th>");
I copied your jquery code before the table2 call.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Table Layout</h1>
<table border="solid 3px" style="font-size: 20px;" width="100%">
<thead>
<tr>
<script>
for (var j = 1; j <= 10; j++) {
console.log("<th><label'>" + j + "</label></th>");
}
</script>
</tr>
</thead>
<tbody>
<script>
function table() {
this.column = col;
}
function col(value1, value2) {
var multiply = (value1 * value2);
return multiply;
}
var table2 = new table();
for (var i = 1; i <= 5; i++) {
console.log("<tr>");
for (var k = 1; k <= 5; k++) {
var value1 = i;
var value2 = k;
console.log("<td>" + table2.column(value1, value2) + "</td>");
}
console.log("</tr>");
}
</script>
</tbody>
</table>
There are these issues:
console.log will not write to the page (the DOM), but to the console area.
The code in the inline script elements will run before the code in the ready handler, so table will not be defined yet.
Defining a constructor with the only purpose to store a function is bad practice. If this is only to do a multiplication then even a plain function is overkill.
As you use jQuery, use it to the full, and populate the table by creating elements with jQuery instead of concatenating strings.
Style your table with CSS classes, not with a style and border attributes. The value you gave to the border attribute is invalid. It accepts values "0" or "1".
The number of cells you generated for the head-row does not correspond to the number of columns in the body of the table.
Here is corrected code:
$(document).ready(function() {
var $titles = [];
for (var j = 1; j <= 5; j++) {
$titles.push($("<th>").append($("<label>").text(j)));
}
$("thead tr").append($titles);
var $rows = [];
for (var i = 1; i <= 5; i++) {
var $row = $("<tr>");
for (var k = 1; k <= 5; k++) {
$row.append($("<td>").text(i * k));
}
$rows.push($row);
}
$("tbody").append($rows);
});
table {
border-collapse: collapse;
font-size: 20px;
width: 100%;
}
td, th {
border: solid 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Table Layout</h1>
<table>
<thead>
<tr>
</tr>
</thead>
<tbody>
</tbody>
</table>
console.log does not add anything to the DOM
You had i inside a loop with j
Your head code ran to 10, the body code to 5
I think you might mean this
function col(value1, value2) {
var multiply = (value1 * value2);
return multiply;
}
$(document).ready(function() {
const $table = $("#table1");
const $thead = $("thead", $table)
const $tbody = $("tbody", $table)
for (let i = 1; i <= 5; i++) {
$thead.append(`<th><label>${i}</label></th>`);
const $tr = $tbody.append('<tr/>')
for (let k = 1; k <= 5; k++) {
$tr.append($(`<td/>`, { text: col(i, k) }));
}
}
});
#table1 {
border-collapse: collapse;
font-size: 20px;
width: 100%
}
th,
td {
border: solid 3px;
text-align: center;
width: 20px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Table Layout</h1>
<table id="table1">
<thead>
</thead>
<tbody>
</tbody>
</table>
To not update the DOM in every loop, push the html to an array
const col = (value1, value2) => value1 * value2;
const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
$(document).ready(function() {
const $table = $("#table1");
const $thead = $("thead", $table);
const $tbody = $("tbody", $table);
const arr = range(1,5,1); // from 1 to 5 step 1
$thead.html(arr.map(i => `<th><label>${i}</label></th>`).join(''));
$tbody.html(arr.map(i => `<tr/>${arr.map(k => `<td>${col(i, k)}</td>`)}</tr>`).join(''))
});
#table1 {
border-collapse: collapse;
font-size: 20px;
width: 100%
}
th,
td {
border: solid 3px;
text-align: center;
width: 20px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Table Layout</h1>
<table id="table1">
<thead>
</thead>
<tbody>
</tbody>
</table>
Simpling adding console.log inside a script tag in you required place will not add the content to the DOM. You have to manipulate the template as string and set it as the html content of the target using html method in jQuery.
Also the loop index used in the for loop was j and you were consoling it with i. The index was looping till 10. But you have only 5 columns inside a row. If that is not purposeful, you have to user loop from 1 to 5
$(document).ready(function () {
maniputalteHeader();
function table() {
this.column = col;
}
function col(value1, value2) {
var multiply = (value1 * value2);
return multiply;
}
var table2 = new table();
let template = '';
for (var i = 1; i <= 5; i++) {
template += "<tr>";
for (var k = 1; k <= 5; k++) {
var value1 = i;
var value2 = k;
template += "<td>" + table2.column(value1, value2) + "</td>";
}
template += "</tr>";
}
$("#tbody").html(template);
});
function maniputalteHeader() {
let template = '';
for (var j = 1; j <= 5; j++) {
template += "<th><label'>" + j + "</label></th>";
}
$("#thead").html(template);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Table Layout</h1>
<table border="solid 3px" style="font-size: 20px;" width="100%">
<thead>
<tr id="thead">
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>

Looping through code to create `<th>` tags but getting `<td>`

This is my code snippet, For every row I am iterating through this array and want to create <th> as many times the loop continues. So for example if loops continues 3 times, 3 <th> should be created with plan names. But the issue is instead of <th> I am having 3 <td>.
Please tell where I am going wrong?
for (j = 0; j < bid[j].length; j++) {
for (k = 0; k < plan["data"].length; k++) {
if (plan["data"][k]) {
if (bid[j] == plan["data"][k]) {
first_row = '<th><b>' + plan["data"][k]["[Plan name]"] + '</b></th>';
var table = document.getElementById("data");
var cell1 = row.insertCell(1);
cell1.innerHTML = first_row;
//$("#data").append(first_row);
}
}
}
}
I want something in this way
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
You can't put a <th> inside a table cell. A cell is either a <td> or <th>. But insertCell always creates <td> cells. Putting <th> inside it doesn't change its type.
Use jQuery to add the <th> to the first row of the table.
for (j = 0; j < bid[j].length; j++) {
for (k = 0; k < plan["data"].length; k++) {
if (plan["data"][k]) {
if (bid[j] == plan["data"][k]) {
$("#data tr:first").append('<th><b>' + plan["data"][k]["[Plan name]"] + '</b></th>');
}
}
}
}

How to delete table cells properly

I am trying to delete table rows and table column. For that i have written two functions. The DelelteRow() and DeleteColumn() delete the cells which have
index greater then zero. But actually one row or column should be deleted at a time. can some one modify my code.
DeleteRow:
function DeleteRows() {
var tbl = document.getElementById('myTable'),
lastRow = tbl.rows.length - 1,
i;
for (i = lastRow; i > 0; i--) {
tbl.deleteRow(i);
}
}
DeleteColumn:
function DeleteColumns() {
var tbl = document.getElementById('myTable'),
lastCol = tbl.rows[0].cells.length - 1,
i, j;
for (i = 0; i < tbl.rows.length; i++) {
for (j = lastCol; j > 0; j--) {
tbl.rows[i].deleteCell(j);
}
}
Something like this will delete one row/column at a time. Your question is not entirely clear which row/column you'd like removed, but your code implies you only want the last row/column removed.
var delRowBtn = document.querySelector('.delRow');
delRowBtn.addEventListener('click', deleteLastRow);
var delColBtn = document.querySelector('.delCol');
delColBtn.addEventListener('click', deleteLastColumn);
var tbl = document.querySelector('table');
function deleteLastRow() {
tbl.deleteRow(tbl.rows.length - 1);
}
function deleteLastColumn() {
var lastCol = tbl.rows[0].cells.length - 1;
for (var i = 0; i < tbl.rows.length; i++) {
tbl.rows[i].deleteCell(lastCol);
}
}
html, body {
font-size: 24px;
}
table {
margin-top: 30px;
}
td {
padding: 10px;
outline: 1px solid lightgrey;
}
<button class="delRow">Delete Row</button>
<button class="delCol">Delete Column</button>
<table>
<tbody>
<tr>
<td>r0c0</td>
<td>r0c1</td>
<td>r0c2</td>
<td>r0c3</td>
<td>r0c4</td>
</tr>
<tr>
<td>r1c0</td>
<td>r1c1</td>
<td>r1c2</td>
<td>r1c3</td>
<td>r1c4</td>
</tr>
<tr>
<td>r2c0</td>
<td>r2c1</td>
<td>r2c2</td>
<td>r2c3</td>
<td>r2c4</td>
</tr>
</tbody>
</table>

Populate table from array using JQuery

I have an array of 16 elements that I want to fill a table. I want it to have 2 rows with 8 cells in each row which is filled with the array. My problem is that when the table is populated, the table populates all elements into one row. I have not had much experience with JQuery and I want to try to get this to work. Any help is appreciated! Here is my code:
//**********Javascript & JQuery**********
var array = [1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8];
var count = 0;
var totalCells = 8;
function writeTable() {
var $table = $('#summaryOfResults');
//Array always includes enough elements to fill an entire row, which is 8 cells. Outer loop determines how many rows to make.
//Inner loop determines the elements to print in the cells for that row.
for (var i = 0; i < array.length / 8; i++) {
$table.find('#body').append('<tr>');
for (var j = 0; j < totalCells; j++) {
$table.append('<td>' + array[count] + '</td>');
count++;
}
$table.append('</tr>');
}
}
//**********HTML**********
<html>
<head>
</head>
<body>
<div id="resultsTable">
<table id='summaryOfResults' border='1'>
<tbody id="body">
<tr>
<th>#</th>
<th>n<sub>i</sub></th>
<th>n<sub>f</sub></th>
<th>E<sub>i</sub> (J)</th>
<th>E<sub>f</sub> (J)</th>
<th>ΔE (J)</th>
<th>ΔE (kJ/mol)</th>
<th>λ (nm)</th>
</tr>
</tbody>
</table>
</div>
<div id="tableButtons">
<button id='copyButton' onclick=''>Copy Table</button>
<button id='clear' onclick='clearTable();'>Clear Table</button>
<button id='write' onclick='writeTable();'>Write Table</button>
</div>
</body>
</html>
First, you have to reset count on every click.
Next, you have to specify where exactly the <td> elements have to be appended to. As for now, you're appending them directly to the <table> :
// your declaration of the table element:
var $table = $('#summaryOfResults');
// ...
// then in nested loop, you're appending the cells directly to the table:
$table.append('<td>' + array[count] + '</td>');
The last thing - .append('</tr>') is not a proper way to create an element object, it should be '<tr/>' , or '<tr></tr>'.
This should be what you're looking for:
function writeTable() {
// cache <tbody> element:
var tbody = $('#body');
for (var i = 0; i < array.length / 8; i++) {
// create an <tr> element, append it to the <tbody> and cache it as a variable:
var tr = $('<tr/>').appendTo(tbody);
for (var j = 0; j < totalCells; j++) {
// append <td> elements to previously created <tr> element:
tr.append('<td>' + array[count] + '</td>');
count++;
}
}
// reset the count:
count = 0;
}
JSFiddle
Alternatively, make a HTML string and append it to the table outside of the loop:
function writeTable() {
// declare html variable (a string holder):
var html = '';
for (var i = 0; i < array.length / 8; i++) {
// add opening <tr> tag to the string:
html += '<tr>';
for (var j = 0; j < totalCells; j++) {
// add <td> elements to the string:
html += '<td>' + array[count] + '</td>';
count++;
}
// add closing </tr> tag to the string:
html += '</tr>';
}
//append created html to the table body:
$('#body').append(html);
// reset the count:
count = 0;
}
JSFiddle

Categories

Resources