Create the table with json data - javascript

I want to create a table with json response and I used reduce function to parse the array.I'm getting reduce not a function error.I want to make the table header as colModels title as header and data of 'Arvind partha','Us West' and so on as td body.
const response={"leads":{"data":[{"UserName":"Arvind Partha","Geo":"US West","LeadStage":"SGL","Firstname":"Julie","Lastname":"Daly","CompanyName":"","Region":"North America","JobTitle":"VP Digital Commerce","Theme":"Digital Retail - Re-Inventing In-Sotre experience","Department":"","Designation":"Vice president","TargetSource":"Database","Medium":"Email","Status":"New","DigitalMarketingOwner":"kishore.natarajan","MQLCallingOwner":"","Practice":"Retail","ServiceLine":"Retail","datecreated":"02-Jun-2020","datemodified":"02-Jun-2020"},{"UserName":"Harish Rajagopalan","Geo":"US West","LeadStage":"MGL","Firstname":"preeti","Lastname":"viswanath","CompanyName":"","Region":"North America","JobTitle":"","Theme":"Oracle Retail - Maximize business value out of oracle retail solutions","Department":"","Designation":"Manager","TargetSource":"","Medium":"","Status":"New","DigitalMarketingOwner":"","MQLCallingOwner":"","Practice":"Retail","ServiceLine":"Retail","datecreated":"17-Jun-2020","datemodified":"18-Jun-2020"}],"ColModels":[{"data":"UserName","title":"User Name"},{"data":"Geo","title":"Geo"},{"data":"LeadStage","title":"Lead Stage"},{"data":"Firstname","title":"First Name"},{"data":"Lastname","title":"Last Name"},{"data":"CompanyName","title":"Company Name"},{"data":"Region","title":"Region"},{"data":"JobTitle","title":"Job Title"},{"data":"Theme","title":"Theme"},{"data":"Department","title":"Department"},{"data":"Designation","title":"Designation"},{"data":"TargetSource","title":"Target Source"},{"data":"Medium","title":"Medium"},{"data":"Status","title":"Status"},{"data":"DigitalMarketingOwner","title":"Digital Marketing Owner"},{"data":"MQLCallingOwner","title":"MQL Calling Owner"},{"data":"Practice","title":"Practice"},{"data":"ServiceLine","title":"Service Line\/Vertical"},{"data":"datecreated","title":"Date Created","formatter":"date","formatoptions":{"newformat":"d-M-yy"}},{"data":"datemodified","title":"Date Modified"}],"types":{"RGL":"RGL","SGL":"Named Lead","MGL":"SAL","PGL":"PGL","BGL":"BGL","Back to marketing":"Back to marketing","Uncategorized lead":""}},"meetings":{"data":[],"ColModels":[{"data":"UserName","title":"User Name"},{"data":"Geo","title":"Geo"},{"data":"RelatedTo","title":"Related to"},{"data":"Subject","title":"Subject"},{"data":"Description","title":"Description"},{"data":"Status","title":"Status"},{"data":"MeetingType","title":"Meeting Type"},{"data":"MeetingHash","title":"Meeting #"},{"data":"Location","title":"Location"},{"data":"startdate","title":"Start Date"},{"data":"enddate","title":"End Date"},{"data":"DurationHours","title":"Duration Hours"},{"data":"DurationMinutes","title":"Duration Minutes"},{"data":"datecreated","title":"Date Created"},{"data":"datemodified","title":"Date Modified"}],"types":{"1st Presentation \/ Meeting":"first_time","Follow-On Meetings":"follow_up","Hold\/Uncategorized":""}},"opportunity":{"data":[],"ColModels":[{"data":"Username","title":"User Name"},{"data":"Geo","title":"Geo"},{"data":"OpportunityGeo","title":"Opportunity Geo"},{"data":"CompanyName","title":"Company Name"},{"data":"SalesStage","title":"Sales Stage"},{"data":"Probability","title":"Probability (%)"},{"data":"PipelineValue","title":"Pipeline Value"},{"data":"CustomerAccountType","title":"Customer Account Type"},{"data":"OpportunityType","title":"Opportunity Type"},{"data":"TeamType","title":"Team Type"},{"data":"LeadSource","title":"Lead Source"},{"data":"ServiceLine","title":"Service Line\/Vertical"},{"data":"datecreated","title":"Date Created"},{"data":"datemodified","title":"Date Modified"},{"data":"salesstagelastmodified","title":"Sales Stage Last Modified"}],"types":{"Identified Opportunities":"Identified","QO under evaluation":"QO_to be approved"}},"reaches":{"data":[],"ColModels":[{"data":"Username","title":"User Name"},{"data":"Geo","title":"Geo"},{"data":"Subject","title":"Subject"},{"data":"Description","title":"Description"},{"data":"Relatedto","title":"Related To"},{"data":"Calloutcome","title":"Call out come"},{"data":"Status","title":"Status"},{"data":"startdate","title":"Start Date"},{"data":"enddate","title":"End Date"},{"data":"Duration","title":"Duration"},{"data":"datecreated","title":"Date Created"},{"data":"datemodified","title":"Date Modified"}],"types":{"Reaches":"Reaches"}},"activities":{"data":[],"ColModels":[{"data":"Username","title":"User Name"},{"data":"Geo","title":"Geo"},{"data":"Subject","title":"Subject"},{"data":"Description","title":"Description"},{"data":"Relatedto","title":"Related To"},{"data":"From","title":"From"},{"data":"datesent","title":"Date Sent"},{"data":"Status","title":"Status"},{"data":"datecreated","title":"Date Created"},{"data":"datemodified","title":"Date Modified"}],"types":{"Activities":"Activities"}},"category":{"leads":{"RGL":"RGL","SGL":"Named Lead","MGL":"SAL","PGL":"PGL","BGL":"BGL","Back to marketing":"Back to marketing","Uncategorized lead":""},"meeting":{"1st Presentation \/ Meeting":"first_time","Follow-On Meetings":"follow_up","Hold\/Uncategorized":""},"opportunity":{"Identified Opportunities":"Identified","QO under evaluation":"QO_to be approved"},"reaches":{"Reaches":"Reaches"},"activities":{"Activities":"Activities"}},"Month":["June-2020"],"Week":["Week 1","Week 2","Week 3","Week 4"],"Team":null};
if((response.leads.data).length) {
var colModels = response.leads.ColModels;
var data = response.leads.data;
console.log(colModels);
console.log(data);
console.log(colModels.title);
colModels.forEach(tr => {
console.log(tr.title);
const thString = tr.title.reduce((res, d) => res + '<td>' + d + '</td>', "");
//$('#tbody').append("<tr>" + trString + "</tr>");
});
$('#thead').html(thString);
data.forEach(tr => {
const trString = tr.data.reduce((res, d) => res + '<td>' + d + '</td>', "");
$('#tbody').append("<tr>" + trString + "</tr>");
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead id="thead"></thead>
<tbody id="tbody"></tbody>
</table>

To achieve expected result, use below option of string concatenation instead of reduce function
Issue from your code is, below mentioned tr is object and reduce works only for arrays.
Removed reduce function and added string concatenation using variable 'head'
let head = '<tr>';
colModels.forEach(tr => {
console.log("tr", tr);
head = head + '<td>' + tr.title + '</td>';
});
Other reduce function is also trying to loop through object instead of array and fixed that using Object.entries
data.forEach((tr) => {
const trString = Object.entries(tr).reduce(
(res, d) => res + "<td>" + d[1] + "</td>",
""
);
$("#tbody").append("<tr>" + trString + "</tr>");
});
Working code for reference
const response={"leads":{"data":[{"UserName":"Arvind Partha","Geo":"US West","LeadStage":"SGL","Firstname":"Julie","Lastname":"Daly","CompanyName":"","Region":"North America","JobTitle":"VP Digital Commerce","Theme":"Digital Retail - Re-Inventing In-Sotre experience","Department":"","Designation":"Vice president","TargetSource":"Database","Medium":"Email","Status":"New","DigitalMarketingOwner":"kishore.natarajan","MQLCallingOwner":"","Practice":"Retail","ServiceLine":"Retail","datecreated":"02-Jun-2020","datemodified":"02-Jun-2020"},{"UserName":"Harish Rajagopalan","Geo":"US West","LeadStage":"MGL","Firstname":"preeti","Lastname":"viswanath","CompanyName":"","Region":"North America","JobTitle":"","Theme":"Oracle Retail - Maximize business value out of oracle retail solutions","Department":"","Designation":"Manager","TargetSource":"","Medium":"","Status":"New","DigitalMarketingOwner":"","MQLCallingOwner":"","Practice":"Retail","ServiceLine":"Retail","datecreated":"17-Jun-2020","datemodified":"18-Jun-2020"}],"ColModels":[{"data":"UserName","title":"User Name"},{"data":"Geo","title":"Geo"},{"data":"LeadStage","title":"Lead Stage"},{"data":"Firstname","title":"First Name"},{"data":"Lastname","title":"Last Name"},{"data":"CompanyName","title":"Company Name"},{"data":"Region","title":"Region"},{"data":"JobTitle","title":"Job Title"},{"data":"Theme","title":"Theme"},{"data":"Department","title":"Department"},{"data":"Designation","title":"Designation"},{"data":"TargetSource","title":"Target Source"},{"data":"Medium","title":"Medium"},{"data":"Status","title":"Status"},{"data":"DigitalMarketingOwner","title":"Digital Marketing Owner"},{"data":"MQLCallingOwner","title":"MQL Calling Owner"},{"data":"Practice","title":"Practice"},{"data":"ServiceLine","title":"Service Line\/Vertical"},{"data":"datecreated","title":"Date Created","formatter":"date","formatoptions":{"newformat":"d-M-yy"}},{"data":"datemodified","title":"Date Modified"}],"types":{"RGL":"RGL","SGL":"Named Lead","MGL":"SAL","PGL":"PGL","BGL":"BGL","Back to marketing":"Back to marketing","Uncategorized lead":""}},"meetings":{"data":[],"ColModels":[{"data":"UserName","title":"User Name"},{"data":"Geo","title":"Geo"},{"data":"RelatedTo","title":"Related to"},{"data":"Subject","title":"Subject"},{"data":"Description","title":"Description"},{"data":"Status","title":"Status"},{"data":"MeetingType","title":"Meeting Type"},{"data":"MeetingHash","title":"Meeting #"},{"data":"Location","title":"Location"},{"data":"startdate","title":"Start Date"},{"data":"enddate","title":"End Date"},{"data":"DurationHours","title":"Duration Hours"},{"data":"DurationMinutes","title":"Duration Minutes"},{"data":"datecreated","title":"Date Created"},{"data":"datemodified","title":"Date Modified"}],"types":{"1st Presentation \/ Meeting":"first_time","Follow-On Meetings":"follow_up","Hold\/Uncategorized":""}},"opportunity":{"data":[],"ColModels":[{"data":"Username","title":"User Name"},{"data":"Geo","title":"Geo"},{"data":"OpportunityGeo","title":"Opportunity Geo"},{"data":"CompanyName","title":"Company Name"},{"data":"SalesStage","title":"Sales Stage"},{"data":"Probability","title":"Probability (%)"},{"data":"PipelineValue","title":"Pipeline Value"},{"data":"CustomerAccountType","title":"Customer Account Type"},{"data":"OpportunityType","title":"Opportunity Type"},{"data":"TeamType","title":"Team Type"},{"data":"LeadSource","title":"Lead Source"},{"data":"ServiceLine","title":"Service Line\/Vertical"},{"data":"datecreated","title":"Date Created"},{"data":"datemodified","title":"Date Modified"},{"data":"salesstagelastmodified","title":"Sales Stage Last Modified"}],"types":{"Identified Opportunities":"Identified","QO under evaluation":"QO_to be approved"}},"reaches":{"data":[],"ColModels":[{"data":"Username","title":"User Name"},{"data":"Geo","title":"Geo"},{"data":"Subject","title":"Subject"},{"data":"Description","title":"Description"},{"data":"Relatedto","title":"Related To"},{"data":"Calloutcome","title":"Call out come"},{"data":"Status","title":"Status"},{"data":"startdate","title":"Start Date"},{"data":"enddate","title":"End Date"},{"data":"Duration","title":"Duration"},{"data":"datecreated","title":"Date Created"},{"data":"datemodified","title":"Date Modified"}],"types":{"Reaches":"Reaches"}},"activities":{"data":[],"ColModels":[{"data":"Username","title":"User Name"},{"data":"Geo","title":"Geo"},{"data":"Subject","title":"Subject"},{"data":"Description","title":"Description"},{"data":"Relatedto","title":"Related To"},{"data":"From","title":"From"},{"data":"datesent","title":"Date Sent"},{"data":"Status","title":"Status"},{"data":"datecreated","title":"Date Created"},{"data":"datemodified","title":"Date Modified"}],"types":{"Activities":"Activities"}},"category":{"leads":{"RGL":"RGL","SGL":"Named Lead","MGL":"SAL","PGL":"PGL","BGL":"BGL","Back to marketing":"Back to marketing","Uncategorized lead":""},"meeting":{"1st Presentation \/ Meeting":"first_time","Follow-On Meetings":"follow_up","Hold\/Uncategorized":""},"opportunity":{"Identified Opportunities":"Identified","QO under evaluation":"QO_to be approved"},"reaches":{"Reaches":"Reaches"},"activities":{"Activities":"Activities"}},"Month":["June-2020"],"Week":["Week 1","Week 2","Week 3","Week 4"],"Team":null};
if((response.leads.data).length) {
var colModels = response.leads.ColModels;
var data = response.leads.data;
console.log('colModels', colModels);
console.log("data", data);
console.log(colModels.title);
let head = '<tr>'
colModels.forEach(tr => {
console.log("tr", tr);
head = head + '<td>' + tr.title + '</td>';
});
$('#thead').html(head + '</tr>');
data.forEach(tr => {
const trString = Object.entries(tr).reduce((res, d) => res + '<td>' + d[1] + '</td>', "");
$('#tbody').append("<tr>" + trString + "</tr>");
});
}
table, tr, td, th{
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead id="thead"></thead>
<tbody id="tbody"></tbody>
</table>
Codepen for reference - https://codepen.io/nagasai/pen/qBbxJrj

Related

How to ignore toggling the highlight of freespace in Javascript bingo?

I'm building a "buzzword bingo" game and am having difficulty with ignoring the onClick for the freespace which should always remain highlighted. I am using Javascript to build the table for me, so applying the css isn't coming easy to me. Here is the js:
function calcRowSize(words) {
return Math.sqrt(words.length);
}
function isEndOfRow(rowSize, index) {
return Number.isInteger(index + 1 / rowSize);
}
function isStartOfRow(rowSize, index) {
return Number.isInteger(index / rowSize);
}
function isFreeSpace(wordCount, index) {
var freeSpaceIndex = Math.floor(wordCount / 2);
return freeSpaceIndex == index;
}
function insertData(words) {
var table = document.getElementById("table");
table.innerHTML=""; // Initialize the table
var tr=""; // Intitialize the table row
var rowSize = calcRowSize(words);
words.forEach((word, index) => {
// Handle 4 scenarios:
// - [start of row] start table row & insert table data
// - [end of row] insert table data & end table row
// - [is the free space] insert blank table data
// - [middle of row] insert table data
if (isStartOfRow(rowSize, index)) {
tr+= '<tr>' ;
tr+= '<td>' + word + '</td>';
} else if (isEndOfRow(rowSize, index)) {
tr+= '<td>' + word + '</td>';
tr+= '</tr>';
} else if (isFreeSpace(words.length, index)) {
tr+= '<td><img src="images/paw.svg"></td>';
} else {
tr+= '<td>' + word + '</td>';
}
// tr+= '<tr>';
// tr+= '<td>' + word + '</td>';
// tr+= '</tr>';
});
table.innerHTML += tr;
}
insertData(shuffle(words));
// Toggle highlighted cells
table.onclick = function(event) {
highlight(event.target);
};
function highlight(td) {
td.classList.toggle('highlight');
}
What is the best way to go about achieving this?

Sorting table using only Javascript

I have this table in which I read the tbody contents from a JSON API and now I need to make it sortable by columns and using only javascript and no Jquery.
Any help would be appreciated
i have found this code which is exactly what i want, but i don't know how to refer to tbodies from my api
var myRequest = new XMLHttpRequest();
myRequest.open('GET', 'https://jsonplaceholder.typicode.com/todos');
myRequest.onload = function () {
var myData = JSON.parse(myRequest.responseText);
dataTable(myData);
};
myRequest.send();
function dataTable(data) {
if (data.length > 0) {
var temp = '';
data.forEach((u) => {
temp += '<tr>';
temp += "<td style='text-align: center'>" + u.userId + '</td>';
temp += "<td style='text-align: center'>" + u.id + '</td>';
temp += '<td>' + u.title + '</td>';
temp += "<td style='text-align: center'>" + u.completed + '</td></tr>';
document.getElementById('data').innerHTML = temp;
});
}
}
<table class="table_id">
<thead>
<tr>
<th>UserID</th>
<th>ID</th>
<th>Title</th>
<th>Completion</th>
</tr>
</thead>
<tbody id="data">
</tbody>
</table>
var myData, asc = {'userId':true, 'id':true, 'title':true, 'completed':true};
var myRequest = new XMLHttpRequest();
myRequest.open('GET', 'https://jsonplaceholder.typicode.com/todos');
myRequest.onload = function () {
myData = JSON.parse(myRequest.responseText);
dataTable(myData);
};
myRequest.send();
function sortTable(key){
myData.sort(function(a, b) {
if(asc[key]){
return a[key] > b[key]? 1:-1;
}
else{
return a[key] > b[key]? -1:1;;
}
});
asc[key] = !asc[key];
document.getElementById('data').innerHTML = '';
dataTable(myData);
}
function dataTable(data) {
if (data.length > 0) {
var temp = '';
data.forEach((u) => {
temp += '<tr>';
temp += "<td style='text-align: center'>" + u.userId + '</td>';
temp += "<td style='text-align: center'>" + u.id + '</td>';
temp += '<td>' + u.title + '</td>';
temp += "<td style='text-align: center'>" + u.completed + '</td></tr>';
document.getElementById('data').innerHTML = temp;
});
}
}
<table class="table_id">
<thead>
<tr>
<th onclick="sortTable('userId');">UserID</th>
<th onclick="sortTable('id');">ID</th>
<th onclick="sortTable('title');">Title</th>
<th onclick="sortTable('completed');">Completion</th>
</tr>
</thead>
<tbody id="data">
</tbody>
</table>
Here is a quick class I made.
You first load your data with dt.load(), then when someone clicks one of the headers, you can add an event that does:
elm.addEventListener("click", (e) => {
prop = e.target.textContent.trim();
dt.sort(prop);
dt.render();
})
class DataTable{
load(arr){
if(arr) this.data = arr;
}
sort(prop){
this.data.sort((a, b) => a[prop] - b[prop]);
}
render(selector="#data"){
if(data.length){
html = data.map(u => {
return [
"<tr>",
`<td style='text-align: center'>${u.userId}</td>`,
`<td style='text-align: center'>${u.id}</td>`,
`<td>${u.title}</td>`,
`<td style='text-align: center'>${u.completed}</td></tr>`
].join("");
}).join("");
document.querySelector(selector).innerHTML = html;
}
}
}
Important - are you wanting to be able to sort multiple columns at the same time or just one column at a time?
Initialize myData outside of onload first. You'll want to be able to access those results outside of onload to sort them. The actual sort function JS offers is a pretty confusing but it's really the only way to go about vanilla JS array sorting.
function sortData(col, asc = true) {
//JS sort function
myData = myData.sort((first, second) => {
//sort logic
if (first[col] == second[col]) {
return 0;
}
if (asc) {
if (first[col] > second[col]) {
return 1;
}
else {
return -1;
}
}
else {
if (first[col] > second[col]) {
return -1;
}
else {
return 1;
}
}
});
//Re-Create table
dataTable(myData);
}
EDIT:
I added in sort logic, but it's definitely possible I messed up. I can't actually test this right now and I haven't touched the sort function in years.

Using Firestore's snapshot.forEach to create a table

I'm trying to output an array filled with Firestore objects onto a table, but just displays the last object above the table
<table class="darkTable">
<thead>
<tr>
<th>List of Available Shows</th>
</tr>
</thead>
<tbody>
<tr>
<div id="showList"></div>
</tr>
</tbody>
</table>
<script>
firebase.firestore().collection('TV Shows').get().then(snapshot => {
var i = 0;
var array = [];
snapshot.forEach(doc => {
array[i] = doc.data().show.name;
//console.log(doc.data().show.name);
//showList.innerHTML = array[i] + "<br />";
showList.innerHTML = '<td>' + array[i] + '</td>';
i++;
});
});
</script>
Is it the way I'm going about the td code lines?
assuming this markup:
<div id="showList"></div>
then it works about like this:
firebase.firestore().collection('TV Shows').get().then(snapshot => {
var showList = document.getElementById('showList');
var html = '<table class="darkTable"><thead><tr>';
html += '<th>List of Available Shows</th>';
/* add further columns into here, alike the one above. */
html += '</tr></thead><tbody>';
snapshot.forEach(doc => {
html += '<tr>';
html += '<td>' + doc.data().show.name + '</td>';
/* add further columns into here, alike the one above. */
html += '</tr>';
});
html += '</tbody></table>';
showList.append(html);
});
You're resetting the entire showList element with every iteration of the loop:
showList.innerHTML = '<td>' + array[i] + '</td>';
I suspect you mean to append to it each time instead or resetting it entirely each time. Maybe try building a string with each iteration, then set the whole thing after the loop is over.

HTML table formatting issue - parsing jSON object into an HTML table

I have some code that grabs a JSON objects and displays it in a HTML table, however the table is not displaying correctly.
I want the table to be displayed like this:
_________________
| Product1 |
==================
| 1852ak | 2016 |
==================
| refurbished |
__________________
Here is my code:
var product = {
"name": "Product1",
"model": "1852ak",
"year": "2016",
"details": "refurbished"
}
$(document).ready(function() {
var row = $('<tr>');
row.append('<tr><td colspan = 2s>' + product.name + '</td></tr>');
row.append('<tr><td>' + product.model + '</td></tr>');
row.append('<td>' + product.year + '</td></tr>');
row.append('<tr><td>' + product.details + '</td></tr>');
$('#sample').append(row);
});
Any help would be greatly appreciated!
The problem is that you're adding rows to your existing rows.
In addition to this, you are considering the table to be one singular 'object', and are adding both the rows and the cells directly to the table. The table cells should be added to their containing rows.
What I would recommend doing is defining three separate rows as independent variables, then adding the cells to their respective rows. As the row has all of its content created, it gets added to the table:
var product = {
"name": "Product1",
"model": "1852ak",
"year": "2016",
"details": "refurbished"
}
$(document).ready(function() {
var table = $('#sample');
var row1 = $('<tr>');
var row2 = $('<tr>');
var row3 = $('<tr>');
row1.append('<td colspan = 2>' + product.name + '</td>');
table.append(row1);
row2.append('<td>' + product.model + '</td>');
row2.append('<td>' + product.year + '</td>');
table.append(row2);
row3.append('<td colspan = 2>' + product.details + '</td>');
table.append(row3);
});
td {
border: 1px solid black;
text-align: center;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="sample"></table>
Hope this helps! :)
Try this Code:
var product =
{
"name":"Product1",
"model":"1852ak",
"year":"2016",
"details":"refurbished"
}
$(document).ready(function()
{
var row =$('table');
row.append ('<tr><td colspan = "2">' + product.name + '</td></tr>');
row.append('<tr><td>' + product.model + '</td><td>' + product.year + '</td></tr>');
row.append ('<tr><td colspan = "2">' + product.details + '</td></tr></table>');
$('#sample').append(row);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sample"></div>
Presuming that $("#sample") is your table

Creating html table using Javascript not working

Basically, I want the user the just change the 'height' variable to how ever many rows he wants, and then store the words which each td in the row should contain, and the code should then generate the table.
My html is just this:
<table id="newTable">
</table>
This is my Javascript:
<script type="text/javascript">
var height = 2; // user in this case would want 3 rows (height + 1)
var rowNumber = 0;
var height0 = ['HeadingOne', 'HeadingTwo']; // the words in each td in the first row
var height1 = ['firstTd of row', 'secondTd of row']; // the words in each td in the second row
var height2 = ['firstTd of other row', 'secondTd of other row']; // the words in each td in the third row
$(document).ready( function() {
createTr();
});
function createTr () {
for (var h=0; h<height + 1; h++) { // loop through 3 times, in this case (which h<3)
var theTr = "<tr id='rowNumber" + rowNumber + "'>"; // <tr id='rowNumber0'>
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
for (var i=0; i<window['height' + rowNumber].length; i++) {
if (i == window['height' + rowNumber].length-1) { // if i==2, then that means it is the last td in the tr, so have a </tr> at the end of it
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td></tr>";
$('#rowNumber' + rowNumber).append(theTr); // append to the end of the Tr
} else {
var theTd = "<td class='row" + rowNumber + " column" + i + "'>" + window['height' + rowNumber][i] + "</td>";
$('#rowNumber' + rowNumber).append(theTr);
}
}
rowNumber += 1;
}
}
</script>
I did 'alert(theTr);' and 'alert(theTd);' and they looked correct. How come this code doesn't generate any table?
You should change the line
$('#rowNumber' + rowNumber).append(theTr);
into
$('#rowNumber' + rowNumber).append(theTd);
You are adding the Tr-Code again in the inner loop, but you actually wanted to add the Td-Code.
All that window["height"+rowNumber] stuff is a poor way to do it. Use an array, and pass it as a parameter to the function so you don't use global variables. And use jQuery DOM creation functions instead of appending strings.
<script type="text/javascript">
var heights = [['HeadingOne', 'HeadingTwo'], // the words in each td in the first row
['firstTd of row', 'secondTd of row'], // the words in each td in the second row
['firstTd of other row', 'secondTd of other row'] // the words in each td in the third row
];
$(document).ready( function() {
createTr(heights);
});
function createTr (heights) {
for (var h=0; h<heights.length; h++) { // loop through 3 times, in this case (which h<3)
var theTr = $("<tr>", { id: "rowNumber" + h});
for (var i=0; i<heights[h].length; i++) {
theTr.append($("<td>", { "class": "row"+h + " column"+i,
text: heights[h][i]
}));
}
$('#newTable').append(theTr); // append <tr id='rowNumber0'> to the table
}
}
</script>
JSFIDDLE

Categories

Resources