Fill table rows with values from an array - javascript

I'm creating a table using JavaScript DOM and I need to insert all the values from the array (thValues) to each of the TH contained in a TR (table row). How I can do it?
let thValues = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5", "Text 6"];
let pickTableZone = document.getElementById("tableDetails");
let table = document.createElement("table");
pickTableZone.appendChild(table);
table.setAttribute("class", "table table-responsive-sm table-striped");
let tableBody = document.createElement("tbody");
table.appendChild(tableBody); //adding tbody to table
//for the length of thValues create table rows
for (let i = 0; i < thValues.length; i++) {
let tableRow = document.createElement("tr");
tableBody.appendChild(tableRow); //adding TR to TBODY
let tableHead = document.createElement("th");
tableRow.appendChild(tableHead); //adding TH to TR
tableHead.setAttribute("scope", "row"); //adding attributes to TH
let text = document.createTextNode(thValues[0]); //Assign each text from the thValues in each TH from the TR's
tableHead.appendChild(text); //adding text to TH
let tableData = document.createElement("td");
tableRow.appendChild(tableData); //adding TD to TR
let textInTD = document.createTextNode("Time 1");
tableData.appendChild(textInTD); //adding text to TD
}
table, th, td {
border: 1px solid gray;
border-collapse: collapse;
padding: 1rem;
}
<div id="tableDetails">

You need two loops: one to populate the head row with th cells; one to create the body rows with td cells. As it stands, you're creating a new row for each header value instead of putting all of them in a single row. You're also putting your head cells in tbody instead of thead.
Here is how you could create the header row.
const thValues = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5", "Text 6"];
const pickTableZone = document.getElementById("tableDetails");
const table = document.createElement("table");
pickTableZone.appendChild(table);
table.setAttribute("class", "table table-responsive-sm table-striped");
const tableHead = document.createElement("thead");
table.appendChild(tableHead); //adding thead to table
const headRow = document.createElement("tr");
tableHead.appendChild(headRow); // Row for the head cells.
// Add each header.
for (let i = 0; i < thValues.length; ++i) {
const headCell = document.createElement("th");
headRow.appendChild(headCell); //adding head cell to head row
const text = document.createTextNode(thValues[i]);
headCell.appendChild(text); //adding text to TH
}
const tableBody = document.createElement("tbody");
table.appendChild(tableBody); //adding tbody to table
// for each row of data
// add a tr to tbody
// for each column (e.g. thValues.length)
// add a td to the tr
table, th, td {
border: 1px solid gray;
border-collapse: collapse;
padding: 1rem;
}
<div id="tableDetails"></div>
It's not clear from your post what you want to put in the tbody since you're just repeating "Time 1" over and over. I've therefore left some pseudocode for populating the body.
As an aside, you should use const instead of let unless you plan on reassigning the variable (for a number of reasons).

I realized what I was missing in my code to achieve what I wanted. I forgot to add an i to let text = document.createTextNode(thValues[i]);
let thValues = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5", "Text 6"];
let pickTableZone = document.getElementById("tableDetails");
let table = document.createElement("table");
pickTableZone.appendChild(table);
table.setAttribute("class", "table table-responsive-sm table-striped");
let tableBody = document.createElement("tbody");
table.appendChild(tableBody); //adding tbody to table
//for the length of thValues create table rows
for (let i = 0; i < thValues.length; i++) {
let tableRow = document.createElement("tr");
tableBody.appendChild(tableRow); //adding TR to TBODY
let tableHead = document.createElement("th");
tableRow.appendChild(tableHead); //adding TH to TR
tableHead.setAttribute("scope", "row"); //adding attributes to TH
let text = document.createTextNode(thValues[i]); //Assign each text from the thValues in each TH from the TR's
tableHead.appendChild(text); //adding text to TH
let tableData = document.createElement("td");
tableRow.appendChild(tableData); //adding TD to TR
let textInTD = document.createTextNode("Time 1");
tableData.appendChild(textInTD); //adding text to TD
}
table, th, td {
border: 1px solid gray;
border-collapse: collapse;
padding: 1rem;
}
<div id="tableDetails">

Related

How do I add an array of objects into an HTML Table?

I am gathering JSON string data on a button click. Each time I click the button another product gets added to the array. The array is an array of objects:
{SKU: "9372983-382L", retail_price: "11.75", list_price: "3.50", product_name: "Tennis balls"}
How would I take this information and insert it into a table? say I have
<div id='table'>
<table>
</table>
</div>
JavaScript:
var prodArr=[{SKU: "9372983-382L", retail_price: "11.75", list_price: "3.50",
product_name: "Tennis balls"}];
function buildTable(data){
var table = document.getElementById('table');
const arr = data;
for(var obj of arr){
var row = document.createElement('tr');
for(var val of Object.values(obj)){
var col = document.createElement('td');
col.textContent = val;
row.appendChild(col);
}
table.appendChild(row);
}
}
buildTable(prodArr);
I would like to add headers for SKU:, retail_price:, list_price: product_name: and a textbox for quantity on each row as well.
You can loop over the array, use Object.values to loop over the values of the object, and use document.createElement to create new table rows to add to the table.
const table = document.getElementById('table');
const arr = [{SKU: "9372983-382L", retail_price: "11.75", list_price: "3.50", product_name: "Tennis balls"}];
for(const obj of arr){
const row = document.createElement('tr');
for(const val of Object.values(obj)){
const col = document.createElement('td');
col.textContent = val;
row.appendChild(col);
}
table.appendChild(row);
}
table, tr, td, th {
border: 1px solid black;
border-collapse: collapse;
padding: 2px;
}
<table id="table">
</table>

Iterate and append to table

Hello i am trying to append some strings from an array to an table. I want every array item to have its own tr element.
The things i have tried so far is this:
const body = document.body
const table = document.createElement('table')
const tr = document.createElement('tr')
const th = document.createElement('th')
const form = document.createElement('form')
const label = document.createElement('label')
table.innerHTML
body.append(table)
tr.innerHTML
table.append(tr)
const thText = ["ID", "First name", "Last name", "Email", "Phone number", "Actions"]
thText.forEach((text)=>{
th.innerHTML = text
tr.append(th);
})
When console.log(th) i get <th> Actions </th> 6 times. but the only thing that is rendered is Actions once.
Would love to get some help. Thanks :)
You're only creating one th element. You'd need to create one for each iteration, so, within the loop:
thText.forEach(text => {
const th = document.createElement('th')
th.innerHTML = text
tr.append(th)
})
There's a few different ways to do this. Here's an example of one way. This method does a few things differently then your example.
It creates and uses a thead element for proper table formatting.
It uses a basic for loop method.
It creates a new th element for each header label in the array, then it appends it to the tr element.
It uses textContent instead of innerHTML
const headerLabels = ["ID", "First name", "Last name", "Email", "Phone number", "Actions"]
const body = document.body
const table = document.createElement('table')
const thead = document.createElement('thead')
const tr = document.createElement('tr')
thead.append(tr)
table.append(thead)
body.append(table)
for (let i = 0; i < headerLabels.length; i++) {
let th = document.createElement('th')
th.textContent=headerLabels[i]
tr.append(th)
}
td, th {
border: 1px solid #ddd;
padding: 8px;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
color: white;
}
<body>
<script src="main.js"></script>
</body>

Using JavaScript to create a table

I'm supposed to create a table like this from scratch using JavaScript and I have no idea how.
Am I supposed to use array for this?
I'm still new to JavaScript and this is my first week of learning it. Thanks for the help!
BMI Health category
Below 18.5 Under weight
Between 18.5 and 23 Normal weight
Between 23 and 27.5 Over weight
Above 27.5 Obese
Creating table in Pure JS:
var table_header = ['BMI', 'Health category'];
var table_rows = [
['Below 18.5', 'Under weight'],['Between 18.5 and 23', 'Normal weight'],
['Between 23 and 27.5', 'Over weight'],['Above 27.5', 'Obese']
];
var dom_body = document.getElementsByTagName('body')[0];
var table = document.createElement('table');
var tbody = document.createElement('tbody');
//use for loop to add row and cells into the table body
var tr = document.createElement('tr');
table_header.forEach(function(value,index){
var td = document.createElement('td'); //table cell
td.innerHTML= value; //set cell value
tr.appendChild(td); //add it into row
})
tbody.appendChild(tr); //add table header
//insert table rows
table_rows.forEach(function(row,index){
var tr = document.createElement('tr');
//append cells for this current row
row.forEach(function(value,index){
var td = document.createElement('td'); //table cell
td.innerHTML= value; //set cell value
tr.appendChild(td); //add it into row
})
tbody.appendChild(tr); //add row
})
//add the table in the dom
table.appendChild(tbody);
dom_body.appendChild(table);

Tds automation in Javascript

const q3Msg = document.getElementById('tableq3');
var value = [{
id: 1,
result: 65,
situation: 'YES'
}, {
id: 2,
result: 22,
situation: 'NO'
}];
function q3Calc() {
q3Msg.classList.remove('hidden');
var table = document.createElement('tbody'), tr, td, row, cell;
for (row = 0; row < value.length; row++) {
console.log(value);
tr = document.createElement('tr');
for (cell = 0; cell < 3; cell++) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = value;
}
table.appendChild(tr);
}
document.getElementById('tableq3').appendChild(table);
}
I have the above code for automate tds in html. But I have the below image as a result.
How can I show each array index in a separate td?
For example, in the first row, I would like show 1 65 YES, and next row 2 22 NO
Your porblem is in td.innerHTML = value;. Replace it with td.innerHTML = value[row][Object.keys(value[row])[cell]]; to get expected value.
const q3Msg = document.getElementById('tableq3');
var value = [{
id: 1,
result: 65,
situation: 'YES'
}, {
id: 2,
result: 22,
situation: 'NO'
}];
function q3Calc() {
q3Msg.classList.remove('hidden');
var table = document.createElement('tbody'),
tr, td, row, cell;
for (row = 0; row < value.length; row++) {
console.log(value);
tr = document.createElement('tr');
for (cell = 0; cell < 3; cell++) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = value[row][Object.keys(value[row])[cell]];
}
table.appendChild(tr);
}
document.getElementById('tableq3').appendChild(table);
}
q3Calc();
td {
padding: 10px;
border: solid 1px #ddd;
}
<div id="tableq3"></div>
The main problems were that you weren't accessing each element (object in this case) in the array (you never used row after assigning it).
Then you never used the keys within each object (you were just calling value which means each time you were basically grabbing the entire array each time).
const q3Msg = document.getElementById('tableq3');
var value = [{
id: 1,
result: 65,
situation: 'YES'
}, {
id: 2,
result: 22,
situation: 'NO'
}];
function q3Calc() {
q3Msg.classList.remove('hidden');
var table = document.createElement('tbody'), tr, td, row, cell;
for (row = 0; row < value.length; row++) {
console.log(value[row]);
tr = document.createElement('tr');
for (let key in value[row]) {
td = document.createElement('td');
td.innerHTML = value[row][key];
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('tableq3').appendChild(table);
}
q3Calc();
td {
padding: 5px;
}
<div id='tableq3'>
</div>
Do you want that?
const q3Msg = document.getElementById('tableq3');
var value = [{
id: 1,
result: 65,
situation: 'YES'
}, {
id: 2,
result: 22,
situation: 'NO'
}];
function q3Calc() {
// q3Msg.classList.remove('hidden');
var table = document.createElement('tbody'), tr, td, row, cell;
for (row = 0; row < value.length; row++) {
console.log(value);
tr = document.createElement('tr');
for (cell = 0; cell < 3; cell++) {
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = '['+value[row].id+','+value[row].result+','+value[row].situation+']';
}
table.appendChild(tr);
}
document.getElementById('tableq3').appendChild(table);
}
q3Calc();
<div id="tableq3"></div>

Bootstrap Table not appearing correctly

I am using JavaScript to loop through some data and build a number of tables and am using Bootstrap with the class table table-hover. This works absolutely fine on all tables except the very last table to be produced. The bottom table is always sqashed and the hover over doesn't work. The columns resize to the correct size but that's about it.
I can't work it out, both tables have the class declared:
No matter how many tables are made it always happens on the very last table. I should point out that I've tried everything I can think of including adding a dummy table within the loop and the last interation but then that makes two squashed tables then.
Update: http://jsfiddle.net/si828/1ksyces5/8/
Code:
$('#tableContainer').empty();
var div = document.getElementById('tableContainer');
for (var i = 0; i < data.length; i++)
{
div.innerHTML = div.innerHTML;
var para = document.createElement("p");
var logo = document.createElement("a");
logo.setAttribute('class', 'glyphicon glyphicon-user');
para.appendChild(logo);
var node = document.createTextNode(" " + data[i].userName + " (" + data[i].userID + ") " );
para.appendChild(node);
var aTag = document.createElement("a");
aTag.setAttribute('data-id-proxy' , data[i].userID);
aTag.setAttribute('class' , 'open-AddUserModal');
aTag.setAttribute('href' ,'#addUserModal');
var span = document.createElement("span");
span.setAttribute('class', 'glyphicon glyphicon-plus');
aTag.appendChild(span);
para.appendChild(node);
para.appendChild(aTag);
para.setAttribute('class', 'text-primary');
div.appendChild(para);
var table = document.createElement('table'), tr, td, row, cell;
table.setAttribute('class', 'table table-hover');
table.setAttribute('id', 'table' + data[i].userID);
table.setAttribute('border', '1');
var header = table.createTHead();
var row = header.insertRow(0);
var cell = row.insertCell(0);
cell.setAttribute('style' , 'width: 20%');
cell.style.backgroundColor = '#eee';
cell.style.fontWeight = 'bold';
cell.innerHTML = "SRM";
var cell = row.insertCell(1);
cell.setAttribute('style' , 'width: 13%');
cell.style.backgroundColor = '#eee';
cell.style.fontWeight = 'bold';
cell.innerHTML = "Target User";
var cell = row.insertCell(2);
cell.setAttribute('style' , 'width: 20%');
cell.style.backgroundColor = '#eee';
cell.style.fontWeight = 'bold';
cell.innerHTML = "Target User Name";
for (row = 0; row < data[i].targetUsers.length; row++)
{
tr = document.createElement('tr');
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = data[i].targetUsers[row].srm;
table.appendChild(tr);
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = data[i].targetUsers[row].targetUser;
td = document.createElement('td');
tr.appendChild(td);
td.innerHTML = data[i].targetUsers[row].targetUserName;
}
document.getElementById('tableContainer').appendChild(table);
}
Based on your JSFiddle, your div.innerHTML = div.innerHTML; on line 10 should be the last statement of your outer for loop (on line 76). Otherwise your table doesn't get a <tbody>, causing bootstrap to malfunction.
Here is the fixed one: http://jsfiddle.net/wsLzk5wq/
If it is only the last table you could add custom css for the last table element by using a child selector.
E.g
HTML:
<div class="parent-container">
<table>
.......
</table>
</div>
CSS:
.parent-container table:last-child {
padding: 10px !important;
.......
}

Categories