Recursively creating tables in Javascript - 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>

Related

Trying to find a way to make new columns with JS

I am building a table with JavaScript. If you check the link you can see it is all in one column, but I need the name. prices, and images in separate columns. I am honestly not sure where to start to do this, so I'm looking for some help.
https://jsfiddle.net/wL28gd10/
JS
window.addEventListener("load", function(){
// ARRAYs
var itemName = ["BLT", "PBJ", "TC", "HC", "GC"];
var itemPrice = ["$1", "$2", "$3", "$4", "$5"];
var itemPhoto =
["images/blt.jpg","images/pbj.jpg","images/tc.jpg","images/hc.jpg","images/gc.jpg"];
//Create HTML Table
var perrow = 1,
table = document.createElement("table"),
row = table.insertRow();
// Loop through itemName array
for (var i = 0; i < itemName.length; i++) {
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemName[i];
// Brreak into next row
var next = i + 1;
if (next%perrow==0 && next!=itemName.length) {
row = table.insertRow();
}
}
// Loop through itemPrice array
for (var i = 0; i < itemPrice.length; i++) {
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemPrice[i];
// Break into next row
var next = i + 1;
if (next%perrow==0 && next!=itemPrice.length) {
row = table.insertRow();
}
}
// Loop through itemPhoto array
for (var i = 0; i < itemPhoto.length; i++) {
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemPhoto[i];
// Break into next row
var next = i + 1;
if (next%perrow==0 && next!=itemPhoto.length) {
row = table.insertRow();
}
}
// Attach table to HTML id "menu-table"
document.getElementById("menu-table").appendChild(table);
});
Just create all of your columns in one loop, like:
for (var i = 0; i < itemName.length; i++) {
var row = table.insertRow();
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemName[i];
cell = row.insertCell();
cell.innerHTML = itemPrice[i];
// Add cell
cell = row.insertCell();
cell.innerHTML = itemPhoto[i];
}
You only really need one loop.
window.addEventListener("load", function(){
// ARRAYs
var itemName = ["BLT", "PBJ", "TC", "HC", "GC"];
var itemPrice = ["$1", "$2", "$3", "$4", "$5"];
var itemPhoto = ["images/blt.jpg","images/pbj.jpg","images/tc.jpg","images/hc.jpg","images/gc.jpg"];
//Create HTML Table
var perrow = 1,
table = document.createElement("table");
// Loop through itemName array
for (var i = 0; i < itemName.length; i++) {
let row = table.insertRow();
// Add cell
var cell = row.insertCell();
cell.innerHTML = itemName[i];
var cell = row.insertCell();
cell.innerHTML = itemPrice[i];
var cell = row.insertCell();
cell.innerHTML = itemPhoto[i];
}
// Attach table to HTML id "menu-table"
document.getElementById("menu-table").appendChild(table);
});
table { border-collapse: collapse; }
table tr td {
border: 1px solid black;
padding: 10px;
background-color: white;
}
<div id="menu-table"></div>

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>

How to check value of table td?

I am trying to create mine field game. "I am very new to Js".
What I have done so far:
var level = prompt("Choose Level: easy, medium, hard");
if (level === "easy") {
level = 3;
} else if (level === "medium") {
level = 6;
} else if (level === "hard") {
level = 9;
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 1; i <= 10; i++) {
var row = document.createElement("tr");
document.write("<br/>");
for (var x = 1; x <= 10; x++) {
var j = Math.floor(Math.random() * 12 + 1);
if (j < level) {
j = "mined";
} else {
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + " ");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
So I create here 2d table and enter 2 random values in rows and columns (mined or clear).
Where I am stuck is:
Check if td = mined it dies otherwise open the box(td) etc.
How do I assign value of td? I mean how can I check which value(mined/clear) there is in the td which is clicked?
Ps: Please don't write the whole code:) just show me the track please:)
Thnx for the answers!
Ok! I came this far.. But if I click on row it gives sometimes clear even if I click on mined row or vice versa!
// create the table
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute('id','myTable');
var tblBody = document.createElement("tbody");
//Create 2d table with mined/clear
for(var i=1;i<=10;i++)
{
var row = document.createElement("tr");
document.write("<br/>" );
for(var x=1;x<=10;x++)
{
var j=Math.floor(Math.random()*12+1);
if(j<level)
{
j = "mined";
}
else{
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + "");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
if(id === "mined")
{
alert("You died");
}else
{
alert("clear");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
I think I do something wrong with giving the table id "myTable"..
Can you see it?
Thank you in advance!
So, the idea would be:
assign a click event to each td cell:
td.addEventListener('click', mycallback, false);
in the event handler (callback), check the content of the td:
function mycallback(e) { /*e.target is the td; check td.innerText;*/ }
Pedagogic resources:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td?redirectlocale=en-US&redirectslug=HTML%2FElement%2Ftd
https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
JavaScript, getting value of a td with id name

Combine HTML Table Rows with Javascript

Is there an easy way to combine rows in an HTML table where the first column is the same? I basically have a table set up like:
<table>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test2</td><td>12345</td><td>12345</td><tr>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test2</td><td>12345</td><td>12345</td><tr>
</table>
and I want it to generate:
<table>
<tr><td>test</td><td>37035</td><td>37035</td><tr>
<tr><td>test2</td><td>24690</td><td>24690</td><tr>
</table>
using jQuery:
var map = {};
$('table tr').each(function(){
var $tr = $(this),
cells = $tr.find('td'),
mapTxt = cells.eq(0).text();
if(!map[mapTxt]){
map[mapTxt] = cells;
} else {
for(var i=1, l=cells.length; i<l; i++){
var cell = map[mapTxt].eq(i);
cell.text(parseInt(cell.text()) + parseInt(cells[i].text()));
}
$tr.remove();
}
});
this is a "dumb" script -- no error handling for cases like different number of cells, fields being non-numeric, etc. Add those if necessary.
Also, depending on how it's generated, it's better to do this server-side.
Here's a plain JavaScript version.
window.onload = function() {
var table = document.getElementById('mytable');
var tr = table.getElementsByTagName('tr');
var combined = Array();
for (i = 0; i < tr.length; i++) {
var td = tr[i].getElementsByTagName('td');
var key = td[0].innerText;
if (!combined[key]) {//if not initialised
combined[key] = Array();
for (j = 0; j < td.length - 1; j++) combined[key][j] = 0;
}
for (j = 0; j < td.length - 1; j++)
combined[key][j] += parseInt(td[j + 1].innerText);
}
while (table.hasChildNodes()) table.removeChild(table.lastChild);
var tbody = document.createElement('tbody');//needed for IE
table.appendChild(tbody);
for (var i in combined) {
tr = document.createElement('tr');
tbody.appendChild(tr);
td = document.createElement('td');
td.innerText = i;
tr.appendChild(td);
for (j = 0; j < combined[i].length; j++) {
td = document.createElement('td');
td.innerText = combined[i][j];
tr.appendChild(td);
}
}
}
This will work on tables with any number of rows and any number of cells. I suppose you want to make the sum for every column, that's what this script does.
And as cwolves mentioned, it is more logical to do this serverside. Users that have JS disabled will see the not so clean uncombined table.

Categories