How to embed a for-loop in a table in JavaScript? - 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';
});

Related

javascript dynamic table filling

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>

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 access value of a dynamically created text node in a later click event?

I have a Javascript project. It's a multiplication table that when click on each cell it should be show the result of that cell.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8"/>
<style>
.tdstyles {
width: 50px;
height: 50px;
text-align: center;
}
</style>
</head>
<body>
<div id="Holder"></div>
</body>
</html>
<script type="text/javascript">
var m;
window.onload = function () {
var table = document.createElement('table');
table.border = 1;
table.cellPadding = 0;
table.cellSpacing = 0;
for (var i = 1; i <= 10; i++) {
var tr = document.createElement('tr');
for (var j = 1; j <= 10; j++) {
m = i*j;
var td = document.createElement('td');
var newContent = document.createTextNode(m);
td.className = "tdstyles";
tr.appendChild(td);
td.appendChild(newContent);
document.getElementsByTagName("td").innerHTML = m;
td.onclick = function () {
console.log();
};
var a = Math.round(Math.random() * 255);
var b = Math.round(Math.random() * 255);
var c = Math.round(Math.random() * 255);
td.style.backgroundColor = "rgb(" + a + "," + b + "," + c + ")";
// myFunction();
}
table.appendChild(tr);
Holder.appendChild(table)
}
};
</script>
How can I save that TextNode when it is in loop and use it when click on that td?
You should save the reference to the text in a closure for each inner iteration so that it can be accessed later. Also note that it's probably a lot easier to assign to the textContent of an element if its only child is going to be a text node.
for (let j = 1; j <= 10; j++) {
const text = i * j;
const td = tr.appendChild(document.createElement('td'));
td.textContent = 'text';
td.className = "tdstyles";
td.onclick = function() {
console.log(text);
};
// ...
Do note that I'm using const and let rather than var - this is very important. var has function scope and is hoisted, which can easily result in confusion, especially when you have any asynchronous code; const and let are much more intuitive.
If you need to run the JavaScript in older browsers, you can wrap the onclick with an IIFE and send the text as an argument.
for (let j = 1; j <= 10; j++) {
var text = i * j;
var td = tr.appendChild(document.createElement('td'));
td.textContent = 'text';
td.className = "tdstyles";
!function (t) {
td.onclick = function() {
console.log(t);
}
}(text);
///...
}

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);
}

Cannot get value from input text of Dynamically created Table

Is that possible to get values from dynamically created table after a button click?
Here is my code for creating a table with an input field:
function tableInsert(row,col){
var body = document.body,
tbl = document.createElement('table');
tbl.style.width = '100px';
tbl.style.border = '1px solid black';
tbl.id="draw_table";
for(var i = 0; i < col; i++){
var tr = tbl.insertRow();
for(var j = 0; j < row; j++){
var input1 = document.createElement("input");
var td = tr.insertCell();
td.appendChild(input1);
td.style.border = '1px solid black';
}
}
body.appendChild(tbl);
console.log(tbl.id);
}
Here is the button click function. It gets the value of the table which is dynamically created:
$("#calculate").click(function(){
var table = document.getElementById('draw_table');
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
console.log(table.rows[r].cells[c].value);//value is undefined . is it right way to get the value
}
}
});
your code retrieve td element while you need value of input tag!
change your code to this:
$("#calculate").click(function(){
var table = document.getElementById('draw_table');
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
console.log(table.rows[r].cells[c].children[0].value);
}
}
}

Categories