Create Table Using JavaScript

Create table using Javascript

This should work (from a few alterations to your code above).

function tableCreate() {  var body = document.getElementsByTagName('body')[0];  var tbl = document.createElement('table');  tbl.style.width = '100%';  tbl.setAttribute('border', '1');  var tbdy = document.createElement('tbody');  for (var i = 0; i < 3; i++) {    var tr = document.createElement('tr');    for (var j = 0; j < 2; j++) {      if (i == 2 && j == 1) {        break      } else {        var td = document.createElement('td');        td.appendChild(document.createTextNode('\u0020'))        i == 1 && j == 1 ? td.setAttribute('rowSpan', '2') : null;        tr.appendChild(td)      }    }    tbdy.appendChild(tr);  }  tbl.appendChild(tbdy);  body.appendChild(tbl)}tableCreate();

Create table rows with Javascript

Your code is very close to working - you just need to create a seperate td element for each iteration of the for loop, and setting the style attribute is much easier when done via the .style property of the element.

Also instead of trying to query for the row you have just created, you can use the return value of the createElement function - it will give you the variable containing the new element.

See this snippet:

const table = document.querySelector('#pixelCanvas');

const colors = ["red", "orange", "green", "blue", "purple"];

const row = document.createElement('tr');
table.appendChild(row);

for (i = 0; i < 5; i++) {
const cell = document.createElement('td');
cell.style.width = "20px";
cell.style.height = "20px";
cell.style.backgroundColor = colors[i];
row.appendChild(cell);
};
<table id="pixelCanvas"></table>

How can I create and populate an HTML table using JavaScript

Here's ony way to insert table into html via javascript. Just iterate over the arrays and create html elements with required data.

const arrayName = ["name1", "name2", "name3"];const arrayAge = [21, 18, 19];const arrayColor = ["green", "blue", "yellow"];const arrayMonth = [1, 6, 4];
const $table = document.getElementById('table');$table.insertAdjacentHTML('afterbegin', createTable());
function createTableRow(data) { const arr = data.map(e => { return `<td>${e}</td>`; }); return `<tr>${arr.join('')}</tr>`;}
function createTable() { const tableRows = arrayName.map((name, i) => { return createTableRow([name, arrayAge[i], arrayColor[i], arrayMonth[i]]); }); return ` <table> <thead> <tr> <td>Name</td> <td>Age</td> <td>Color</td> <td>Month</td> </tr> </thead> <tbody> ${tableRows.join('')} </tbody> </table> `; }
table,table tr,table td {  border: 1px solid;  border-collapse: collapse;  text-align: center;}
<div id="table" class="row clearfix"></div>

It is possible to create two table with js?

Nice question :-) You only need one loop for each table. I did it with a for loop. I added a function that outputs a random image.

const t1 = document.querySelector('.top');
const t2 = document.querySelector('.side');

const spaces2 = [
",
",
",
",
",
"br>];

const spaces = [
",
",
",
",
",
",
",
",
];

let tr = document.createElement('tr');
for (let i = 0; i < 3; i++) {
let td = document.createElement('td');
td.innerHTML = getRandomElement(spaces2);
tr.append(td);
}
t1.append(tr);

// t2
for (let i = 0; i < 4; i++) {
let tr = document.createElement('tr');
let td = document.createElement('td');
td.innerHTML = getRandomElement(spaces);
tr.append(td);
t2.append(tr);
}

function getRandomElement(items) {
return items[Math.floor(Math.random()*items.length)];
}
small {
font-size: 16px;
padding-left:5px;
}

table {

}
table td {
border: 2px solid #999;
padding: 5px;
}
<h2>Table 1<small>3 cols and 1 row</small></h2>
<table class="top"></table>
<h2>Table 2<small>1 cols with 4 rows</small></h2>
<table class="side"></table>

creating table using JavaScript

Create a row within the loop, generate raw HTML cells(td elements) and update the content of the raw element(tr).

var staffs = [    {"name": "James", "gender": "male", "dateofbirth":2011, "joined": "1997", "num_hires": 24000},    {"name": "Anna", "gender": "female", "dateofbirth": 2013, "joined": "1980", "num_hires": 12000},    {"name": "Ken", "gender": "male", "dateofbirth": 2013, "joined": "1980", "num_hires": 13000},    {"name": "Tom", "gender": "male", "dateofbirth": 203, "joined": "1995", "num_hires": 12500}];
function createheader() { var table = document.getElementById("table"); var header = table.createTHead(table); var row = header.insertRow(0);
var head = ["Name", "Gender", "Date of Birth", "join year", " Rentals"]; for (let i = 0; i < head.length; i++) { let cell = document.createElement("td"); cell.innerText = head[i]; row.append(cell); }}
function populatebody() { var table = document.getElementById("table"); var tbody = table.createTBody(table);
for (var i = 0; i < staffs.length; i++) {
var row = tbody.insertRow(0); row.innerHTML = ` <td>${staffs[i].name}</td> <td>${staffs[i].gender}</td> <td>${staffs[i].dateofbirth}</td> <td>${staffs[i].joined}</td> <td>${staffs[i].num_hires}</td> `; }}
createheader();populatebody();
<table id="table"></table>

Creating table from Object in html/javascript

Have a look at this

Using a filter and a few maps, we can create the complete HTML in one go

I also removed your inline event handler and delegated to the main container

Additionally I added the currency and aligned the cells with numbers

result = [{ "Plan ID": 0, "ID": 23, "[Plan name]": "Tab A", "Emp Only": 133.90, "Emp + Spouse/Partner": 161.30, "Emp + Child(ren)": 53.30, "Emp + Family": 186.20, " max contrib. / Emp only": 3000, " max contrib. / Emp + dependents": 6000, "Emp ded. / Emp only": 6650, "Emp ded. / Emp + dependents": 13300 }, { "Plan ID": 0, "ID": 23, "[Plan name]": "Tab B", "Emp Only": 33.90, "Emp + Spouse/Partner": 161.1, "Emp + Child(ren)": 55.30, "Emp + Family": 180.8, " max contrib. / Emp only": 3000, " max contrib. / Emp + dependents": 6000, "Emp ded. / Emp only": 660, "Emp ded. / Emp + dependents": 5500 }];

const main = document.getElementById('main');
main.innerHTML = result.map((res,i) => {
const header = res["[Plan name]"]; // get the plan from the entry
const idx = i+1;
return `<div class="table_container">
<table id="table${idx}" class="checkboxdiv">
<tr>
<th>${header}<input type="checkbox" id="${idx}" name="table${idx}" value="table${idx}"> </th>
</tr>
${Object.entries(res)
.filter(([key,val]) => key.includes('Emp')) // filter the Emp
.map(([key,val]) => `<tr><td class="amt">$${val.toFixed(2)}</td></tr>`).join('')}
</table></div>`}).join('');

// replaces your inline event handler using delegation
main.addEventListener("click",function(e) {
const tgt = e.target;
if (tgt.type==="checkbox") console.log(tgt.id)
})
.amt {text-align:right; }
<div id="main">

</div>


Related Topics



Leave a reply



Submit