javascript dynamic table filling - javascript

I have multiple arrays lets say:
var animals = ["cow","horse","rabbit","elephant","donkey","monkey","zebra"];
var food = ["apple","banana","pear","melon","grape","peach","pineapple"];
I want to put this in 4-column table dynamically. if click on animals picture the animals array would fill the table, if food, then food array would fill the table.
So, lets say I have
<table class="myTable"></table>
Then need javascript
import $ from "https://cdn.skypack.dev/jquery#3.6.1";
var animals = ["cow","horse","rabbit","elephant","donkey","monkey","zebra"];
var food = ["apple","banana","pear","melon","grape","peach","pineapple"];
var $table = $('.myTable');
for (var i = 0; i < food.length; i++){
var $aSingleContent = '<tr><td>'+food[i]+'</td></tr>';
$table.append($aSingleContent);
}
This would display all food items in 1 column. Now I need to divide this by 4 - because 4 columns in a row

because of <tr> in line var $aSingleContent = '<tr><td>'+food[i]+'</td></tr>'; makes your javascript create a new row for every element in array. we need to keep count the amount of data that had filled a row. if a row has 4 columns columnCount === 4, then we create a new row.
const food = ["apple","banana","pear","melon","grape","peach","pineapple"];
const $table = $('.myTable');
let $aSingleContent = "<tr>", columnCount = 0;
for (var i = 0; i < food.length; i++){
if(columnCount === 4) {
columnCount = 0;
$aSingleContent += '</tr><tr>';
}
$aSingleContent += '<td>'+food[i]+'</td>';
columnCount++;
}
$aSingleContent += "</tr>"
$table.append($aSingleContent);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="myTable" border></table>

You can try this:
window.onload = function() {
var animals = ["cow","horse","rabbit","elephant","donkey","monkey","zebra"];
var food = ["apple","banana","pear","melon","grape","peach","pineapple"];
var table = document.getElementById("table");
var i = 0, r = 0;
while(i < animals.length) {
var row = table.insertRow(r);
for (var c = 0; c < 4; c++) {
var cell = row.insertCell(c);
cell.appendChild(document.createTextNode(animals[i] ? animals[i] : ''));
i++;
}
r++;
}
document.body.appendChild(table);
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table" cellpadding="1" cellspacing="1">
</table>
Hope this help!

If you have food array more than you provide you can use this one.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.1.slim.min.js" integrity="sha256-w8CvhFs7iHNVUtnSP0YKEg00p9Ih13rlL9zGqvLdePA=" crossorigin="anonymous"></script>
</head>
<body>
<table class="myTable" border="1">
</table>
<script>
var animals = ["cow","horse","rabbit","elephant","donkey","monkey","zebra"];
var food = ["apple","banana","pear","melon","grape","peach","pineapple", "a","b","c","d"];
var $table = $('.myTable');
var $aSingleContent = '';
var to = 0;
var from = 3;
for (var i = 0; i < food.length; i++){
if (i==to)
{ $aSingleContent += '<tr>'; }
$aSingleContent += '<td>'+food[i]+'</td>';
if (i==from)
{
$aSingleContent += '</tr>';
to = to + 4;
from = from + 4;
}
}
$table.append($aSingleContent);
</script>
</body>
</html>

Related

Recursively creating tables in Javascript

I just started to create something that creates a table with x rows and you can put however many columns in a row that you want. Whenever I attempt to run it, it only creates one cell. How do I fix this?
var xio = parseInt(prompt("How many weighted areas are in this subject?"))
for (i = 5; xio > 0; xio--) {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
cell1.innerHTML = "NEW CELL1";
var firstRow = document.getElementById("myTable").rows[xio];
var x = firstRow.insertCell(0);
x.innerHTML = "New cell";
}
<table id="myTable"></table>
There's no prompt for second input so even if the rest of your code was ok (which it isn't) there'd be only one cell. As far as the cells/columns you need to create them in a loop within the loop that creates the rows. Note how the loops syntax is in demo.
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
cell.textContent = "NEW CELL";
}
}
td {
border: 2px ridge #333;
text-align: center;
}
<table id="xTable"></table>
You can simply create table by using the below function
function makeTableHTML(myArray)
{
var result = "<table border=1>";
for(var i=0; i<myArray.length; i++) {
result += "<tr>";
for(var j=0; j<myArray[i].length; j++){
result += "<td>"+myArray[i][j]+"</td>";
}
result += "</tr>";
}
result += "</table>";
return result;
}
In your code, you are trying to select table.rows[xio] but if xio === 5, the row number 5 doesn't exist yet (because it's iteration 1), so it crashes.
Do it the other way around. Instead of looping by decreasing xio, loop by increasing i.
var xio = parseInt(prompt("How many weighted areas are in this subject?")),
table = document.getElementById("myTable");
for (i = 0; i < xio; i++) {
var row = table.insertRow(0),
cell1 = row.insertCell(0);
cell1.innerHTML = "NEW CELL1";
}
<table id="myTable"></table>
var rQty = parseInt(prompt("Number of Rows"), 10);
var cQty = parseInt(prompt("Number of Columns"), 10);
var table = document.getElementById("xTable");
for (let i = 0; i < rQty; i++) {
var row = table.insertRow();
for (let j = 0; j < cQty; j++) {
var cell = row.insertCell();
cell.textContent = "NEW CELL";
}
}
td {
border: 2px ridge #333;
text-align: center;
}
<table id="xTable"></table>

How to embed a for-loop in a table in JavaScript?

I have to generate a sequence with a difference of 9. starting from 7. sequence should have 20 terms. I have tested my for loop and its working fine. Question is, how do I embedd this for loop in a table in javascript? Just want the table to have one column (sequence in for loop)
<script type="text/javascript">
var i;
var p;
for (i = 0; i < 20; i++) {
p = i * 9 + 7;
document.writeln(p + "<br>");
}
</script>
Use a loop to create the relevant HTML element objects and set their values within your Javascript:
var table = document.createElement("table");
var i;
var p;
for (i = 0; i < 20; i++) {
var row = document.createElement("tr");
var row_data = document.createElement("td");
p = i * 9 + 7;
row_data.innerHTML = p;
row_data.style = "border: 1px solid black";
row.appendChild(row_data);
table.appendChild(row);
}
document.body.appendChild(table);
Declare a table in html and give it an id
<table id="table"></table>
Then, get that table in your javascript and add one row, column in each iteration
<script type="text/javascript">
var i;
var p;
var table = document.getElementById("table");
for (i = 0; i < 20; i++) {
p = i * 9 + 7;
table.innerHTML = `${table.innerHTML}<tr><td>${p}</td></tr>`;
}
</script>
let table = '<table><tbody>';
for (let i = 0; i < 20; i++) {
table += (`<tr><td>${i}</td><td>${i * 9 + 7}</td></tr>`);
}
table += '</tbody></table>';
document.body.innerHTML = table;
Array.from(document.getElementsByTagName('td'))
.forEach((td) => {
td.style.border = '1px solid green';
td.style.width = '40px';
td.style.textAlign = 'right';
td.style.paddingRight = '20px';
});
Array.from(document.getElementsByTagName('table'))
.forEach((table) => {
table.style.border = '2px solid';
});

Javascript for add cells in table

I have a problem. I need insert cell in a row. The content of cell is an element of an array. But is duplicate... Here my code:
function addFila() {
var iframe = document.getElementById('myFrame');
var table = iframe.contentDocument.getElementsByClassName("head_to_head h2h_home")[0];
var row = table.insertRow(1);
var fila = ["fecha", "liga", "equipolocal", "equipovisitante", "goleslocal", "golesvisitante"];
for (let i = 0; i < 6; i++) {
row.insertCell(i);
for (let x = 0; x <= fila.length; x++) {
row.insertCell(i).innerHTML = fila[i];
}
}
}
What is wrong?
row.insertCell() return new cell. If you want to create cell and use it you should save created cell in variable. You get duplicate because you call insertCell twice. I hope code below can help you
var table = document.querySelector(".table");
var row = table.insertRow(-1);
var fila = ["fecha", "liga", "equipolocal", "equipovisitante", "goleslocal", "golesvisitante"];
for (let i = 0; i < fila.length; i++) {
const insertedCell = row.insertCell(i);
insertedCell.textContent = fila[i];
}
table td {
border: 1px solid lime;
}
<table class="table">
<tbody>
<tr>
<td>cell_1_1</td>
<td>cell_1_2</td>
</tr>
<tr>
<td>cell_2_1</td>
<td>cell_2_2</td>
</tr>
</tbody>
</table>

Javascript code that should make a table and run on page load [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Javascript should run when the page loads, create a table with 10 rows and 10 columns and adds it to div "funky", the cells of the table should contain the text "N M" where N is the minumum of the row and column index and M is the maximum of the row and column index,cells in even numbered columns should have the text colour purple. here are my javascript and html codes
function go() {
var ROWS = 10;
var COLS = 10;
var out = document.getElementsByClassName("funky");
var table = document.createElement("table");
table.border = 1;
for (var i = 0; i <= ROWS; i += 1) {
var row = document.createElement("row");
if (i == 2) {
row.Fontweight = "bold";
}
for (var j = 0; j < COLS; j += 2) {
var col = document.createElement("cell");
col.innerHTML = i + " " + j;
if (j / 2 === 0) {
col.style.color = "purple";
}
row.appendChild(col);
}
table.appendChild(row);
document.getElementsByClassName("table");
}
}
onload = go();
<html>
<head>
<title>Question 2</title>
<script src="question2.js" type="text/javascript"></script>
<head>
<body>
<div class="funky"></div>
</body>
<html>
Replace HTML Code To :
<html>
<head>
<title>Question 2</title>
<script src="question2.js" type="text/javascript"></script>
</head>
<body onload="javascript:go();">
<div class="funky"></div>
</body>
</html>
Replace JS Code To :
function go() {
var ROWS = 10;
var COLS = 10;
var out = document.getElementsByClassName("funky")[0];
var table = document.createElement("table");
table.style.border = "1px solid #000";
table.style.borderCollapse = "collapse";
for (var i = 0; i <= ROWS; i += 1) {
var row = document.createElement("tr");
if (i == 2) {
row.style.fontWeight = "bold";
}
for (var j = 0; j < COLS; j += 1) {
var col = document.createElement("td");
col.innerHTML = i + " " + j;
if (j % 2 === 0) {
col.style.color = "purple";
}
row.appendChild(col);
}
table.appendChild(row);
}
out.appendChild(table);
}
You need to use MOD Operator to understand is it even or not. You need to use style property before using border property.
You have several mistakes in your code.
When you use getElementsByClassName you need to access them by
index like this
var out = document.getElementsByClassName("funky")[0];
You need to append table after creating it to div then it will be
show on page.
You need to create tr instead of row and td instead of cell.
function go() {
var ROWS = 10;
var COLS = 10;
var out = document.getElementsByClassName("funky")[0];
var table = document.createElement("table");
table.border = 1;
for (var i = 0; i <= ROWS; i ++) {
var row = document.createElement("tr");
if (i == 2) {
row.style.fontWeight = "bold";
}
for (var j = 0; j < COLS; j += 2) {
var col = document.createElement("td");
col.innerHTML = i + " " + j;
if (j / 2 === 0) {
col.style.color = "purple";
}
row.appendChild(col);
}
table.appendChild(row);
document.getElementsByClassName("table");
}
out.appendChild(table);
}

How to create rows cell loop in js

I am trying to sum a table column total.
Here is an example of only two column for test purposes. I want to calculate table column's item total using a javascript loop.
How to create the loop if we don't know how many rows and columns are inside in table? I hope you understand what I mean and also hope for your kindly suggestion.
<p><b>Student at Stanford University 2013-2014</b></p>
<table><tr><th>Faculty (Subject)</th><th>Student 2013</th><th>Student 2014</th></tr></table>
<table id="sdtable">
<tr><th>Business</th><td>12922</td><td>11420</td></tr>
<tr><th>Earth Sciences</th><td>4320</td><td>4611</td></tr>
<tr><th>Education</th><td>14560</td><td>13490</td></tr>
<tr><th>Engineering</th><td>8750</td><td>9863</td></tr>
<tr><th>Humanities & Sciences</th><td>7819</td><td>7219</td></tr>
<tr><th>Medicine</th><td>5219</td><td>4200</td></tr>
</table>
<button onclick="Calculate()">Calculate</button>
<div id="Studentf" class="Studentf"></div>
<div id="Students" class="Students"></div>
<div id="Studentt" class="Studentt"></div>
and
var ftable = document.getElementById("sdtable");
var i= 0;
var sumFirst=0;
var sumSecond=0;
var sumTotal=0;
function Calculate(){
for (i=0;i<ftable.rows.length; i++){
sumFirst=sumFirst+parseInt(ftable.rows[i].cells[1].innerHTML);
sumSecond=sumSecond+parseInt(ftable.rows[i].cells[2].innerHTML);
}
sumTotal=sumFirst+sumSecond;
document.getElementById("Studentf").innerHTML +="<b>Student in 2013 = </b>" +sumFirst;
document.getElementById("Students").innerHTML +="<b>Student in 2014 = </b>" +sumSecond;
document.getElementById("Studentt").innerHTML +="<b>Total Student = </b>" +sumTotal;
}
The key here is that you need to use cells collection to get number of columns that can change when you add new years to the table. You will also have to dynamically create elements for summary information per year.
Here is an example:
var ftable = document.getElementById("sdtable");
var i = 0;
var sumFirst = 0;
var sumSecond = 0;
var sumTotal = 0;
function Calculate() {
var rows = ftable.tBodies[0].rows,
header = ftable.tHead.rows[0],
cells = ftable.tBodies[0].rows[0].cells,
years = [];
for (var i = 0; i < rows.length; i++) {
for (var j = 1; j < cells.length; j++) {
if (!years[j]) years[j] = 0;
years[j] += parseInt(rows[i].cells[j].innerHTML);
}
}
sumTotal = years.reduce(function(prev, curr) {
return prev + curr;
}, 0);
var sum = document.getElementById("sum");
sum.innerHTML = '';
for (var j = 1; j < cells.length; j++) {
console.log(header.cells[j])
sum.insertAdjacentHTML('afterbegin', '<p><b>' + header.cells[j].innerHTML + '</b> = ' + years[j] + '</p>');
}
sum.insertAdjacentHTML('beforeend', "<b>Total Student = </b>" + sumTotal);
}
Demo: http://jsfiddle.net/x2sscpxL/1/
The table should probably look more like:
<table>
<thead>
<tr><th>Faculty (Subject)</th><th>Student 2013</th><th>Student 2014</th></tr>
</thead>
<tbody id="sdtable">
<tr><th>Business</th><td>12922</td><td>11420</td></tr>
<tr><th>Earth Sciences</th><td>4320</td><td>4611</td></tr>
<tr><th>Education</th><td>14560</td><td>13490</td></tr>
...
</tbody>
<tfoot>
<tr><th>Totals:</th><th></th><th></th></tr>
</table>
to split the header, body and footer into separate table sections. The function should then be like:
function calculate(){
// Get a reference to the tBody
var tBody = document.getElementById('sdtable');
if (!tBody) return;
var row, rows = tBody.rows;
var cell, cells;
var cellTotals = {};
// For each row in the body
for (i=0, iLen=rows.length; i<iLen; i++) {
row = rows[i];
cells = row.cells;
// Add the cells in each column, starting on the second column
// i.e. starting with cell index 1
for (var j=1, jLen=cells.length; j<jLen; j++) {
cell = cells[j];
if (j in cellTotals) {
cellTotals[j] += Number(cell.textContent || cell.innerText);
} else {
cellTotals[j] = Number(cell.innerHTML);
}
}
}
// Write the totals into the footer
var tFoot = tBody.parentNode.tFoot;
row = tFoot.rows[0];
for (var k=1; k<jLen; k++) {
row.cells[k].innerHTML = cellTotals[k];
}
}
Note that by convention, variables with a name starting with a capital letter are reserved for constructors (though constants usually are all caps).
Here is calculation of table witn n rows and n columns
Note: header cells wrapped in thead section
var ftable = document.getElementById("sdtable");
var tbody = ftable.getElementsByTagName("tbody")[0]
var columnsCount = ftable.rows[0].cells.length;
var sumTotal = [];
for(i=0; i<columnsCount;i++)
sumTotal.push(0); //here initialize with zero
function Calculate(){
for (i=0;i<tbody.rows.length; i++){
for (j=0; j<columnsCount; j++)
if (tbody.rows[i].cells[j] && tbody.rows[i].cells[j].innerHTML)
sumTotal[j] += parseInt(tbody.rows[i].cells[j].innerHTML);
}
return sumTotal;
}
sumTotal = Calculate();
tfootrow = ftable.tFoot.rows[0];
console.log(tfootrow)
for(i=0; i<sumTotal.length; i++){
tfootrow.insertCell(i).innerHTML = sumTotal[i];
}
<table id="sdtable">
<thead>
<tr>
<th>Business</th>
<th>Earth Sciences</th>
<th>Education</th>
<th>Engineering</th>
<th>Humanities & Sciences</th>
<th>Medicine</th>
</tr>
</thead>
<tbody>
<tr><td>12922</td><td>11420</td></tr>
<tr><td>4320</td><td>4611</td></tr>
<tr><td>14560</td><td>13490</td></tr>
<tr><td>8750</td><td>9863</td></tr>
<tr><td>7819</td><td>7219</td></tr>
<tr><td>5219</td><td>4200</td></tr>
<tr><td></td><td>1</td><td>2</td></tr>
</tbody>
<tfoot>
<tr></tr>
</tfoot>
</table>

Categories