Here's an example of my JSON:
{
"2017-05-06": {
"13": {
"Chris": "2", "Ian": "3"
},
"14": {
"Chris": "4", "Rob": "4"
},
"16": {
"Ian": "3", "Rob": 2
}
}
}
Ideally, I need it to use JS to be able to display it in a table, and with any gaps filled with zeros, the column headers (hours) in sequence, even if they're empty, and total columns and rows.
2017-05-06
13 14 15 16 T
Chris 2 4 0 0 6
Ian 3 0 0 3 6
Rob 0 4 0 2 6
Total 5 8 0 5 18
I've no idea where to start, so would really appreciate any assistance or advice!
You could collect all totals in the given object and collect the rows and columns as well as the missing ones, then iterate rows and columns and build the table with the given data.
var data = { "2017-05-06": { 13: { Chris: "2", Ian: "3" }, 14: { Chris: "4", Rob: "4" }, 16: { Ian: "3", Rob: 2 } } };
Object.keys(data).forEach(function (k) {
var table = document.createElement('table'),
rows = [],
cols = Object.keys(data[k])
.sort(function (a, b) { return a - b; })
.reduce(function (r, a) {
var i = +r[r.length - 1];
while (++i < a) {
r.push(i.toString());
}
r.push(a);
return r;
}, []);
data[k].total = { total: 0 };
cols.forEach(function (l) {
var sub = data[k][l] || {};
Object.keys(sub).forEach(function (m) {
if (rows.indexOf(m) === -1) {
rows.push(m);
}
data[k].total[m] = (data[k].total[m] || 0) + +sub[m];
data[k].total.total += +sub[m];
sub.total = (sub.total || 0) + +sub[m];
});
});
cols.unshift('');
cols.push('total');
rows.unshift('');
rows.push('total')
rows.forEach(function (r) {
var tr = document.createElement('tr');
cols.forEach(function (c) {
var t = document.createElement(r && c ? 'td' : 'th'),
v = r && c ? (data[k][c] || {})[r] || 0 : r || c;
t.appendChild(document.createTextNode(v));
if (v == +v) {
t.style.textAlign = 'right';
}
tr.appendChild(t);
});
table.appendChild(tr);
});
document.body.appendChild(document.createTextNode(k));
document.body.appendChild(document.createElement('br'));
document.body.appendChild(table);
});
I would start by making two arrays, one for the rows and one for the columns, that contain all the row and column titles/keys that you want to display. Then iterate the row array/col array to build a table, if there is data for row+col write it otherwise write zero. Keep total variables summing as you go.
var data = {
"2017-05-06": {
"13": {"Chris": "2", "Ian": "3"},
"14": {"Chris": "4", "Rob": "4"},
"16": {"Ian": "3", "Rob": 2}
}
};
var d = data['2017-05-06'];
var keys = Object.keys(d).sort();
// from the lowest and highest "hours" values, create an array containing everything in between too
var hours = [];
for (var i = keys[0]; i <= keys[keys.length - 1]; i++) {
hours.push(i);
}
// get the unique names
var names = [];
for (var k in d) {
for (var l in d[k]) {
if (names.indexOf(l) === -1) names.push(l);
}
}
var colTotals = {'total':0};
var tbl = "<table><thead><tr><th>Name</th>";
for (var i=0,h; h = hours[i]; i++) {
tbl += "<th>" + h + "</th>";
colTotals[h] = 0;
}
tbl += "<th>Total</th></tr></thead><tbody>";
for (var i=0,n; n = names[i]; i++) {
tbl += "<tr><td>" + n + "</td>";
var total = 0;
for (var j=0,h; h = hours[j]; j++) {
tbl += "<td>";
// if data contains values for this row/col, add to total and table, otherwise put a zero
if (d[h] && d[h][n]) {
total += (d[h][n] - 0);
colTotals[h] += (d[h][n] - 0);
tbl += d[h][n];
} else {
tbl += "0";
}
tbl += "</td>";
}
colTotals['total'] += total;
tbl += "<td>" + total + "</td></tr>";
}
tbl += "<tr><td></td>";
for (var i=0,h; h = hours[i]; i++) {
tbl += "<td>" + colTotals[h] + "</td>";
}
tbl += "<td>" + colTotals['total'] + "</td></tr>";
tbl += "</tbody></table>";
document.getElementById('t').innerHTML = tbl;
<div id='t'></div>
My solution is I take out the min hour and the max hour as the column names, and retrieve the different names as the names of the rows, then loop the rows and columns and add data from the data object to the table, if there is no data, default is 0.
var jsonData = `{
"2017-05-06": {
"13": {
"Chris": "2", "Ian": "3"
},
"14": {
"Chris": "4", "Rob": "4"
},
"16": {
"Ian": "3", "Rob": 2
}
}
}`;
var objData, obj, arrName, arrHour, minHour, maxHour,
table, row, cell, caption;
objData = JSON.parse(jsonData);
obj = objData["2017-05-06"];
arrHour = Object.keys(obj);
minHour = Math.min(...arrHour);
maxHour = Math.max(...arrHour);
arrName = [];
for (let i in obj) {
for (let j in obj[i]) {
if (!arrName.includes(j)) {
arrName.push(j);
}
}
}
table = document.createElement("table");
table.cellPadding = 2;
table.style.fontFamily = "monospace";
table.style.textAlign = "center";
caption = table.createCaption();
caption.innerText = "2017-05-06";
caption.style.textAlign = "left";
row = table.insertRow();
row.insertCell();
for (let i = minHour; i <= maxHour; i++) {
cell = row.insertCell();
cell.innerText = i;
}
cell = row.insertCell();
cell.innerText = "Tt";
for (let i = 0; i < arrName.length; i++) {
let totalRow = 0;
row = table.insertRow();
cell = row.insertCell();
cell.style.textAlign = "left";
cell.innerText = arrName[i];
for (let j = minHour; j <= maxHour; j++) {
cell = row.insertCell();
if (obj[j] !== undefined) {
if (obj[j][arrName[i]] !== undefined) {
cell.innerText = obj[j][arrName[i]];
totalRow += +obj[j][arrName[i]];
}
else {
cell.innerText = 0;
}
}
else {
cell.innerText = 0;
}
}
cell = row.insertCell();
cell.innerText = totalRow;
}
row = table.insertRow();
row.innerText = "Total";
for (let i = 0; i <= maxHour - minHour + 1; i++) {
let totalCol = 0;
cell = row.insertCell();
for (let j = 0; j < arrName.length; j++) {
totalCol += +table.rows[j + 1].cells[i + 1].innerText;
}
cell.innerText = totalCol;
}
document.body.appendChild(table);
Related
what I want is on save click to show another table like below where the second column(Questions) has sub-columns depending maximum L value a row has:
unit Question
unit1 23(L1)
unit2 23(L3)
unit3 24(L3)
unit4 6(L2)
unit4 10(L4)
unit5 7(L1)
unit5 10(L6)
unit6 10(L2)
unit 7(L4)
var x = [];
function getval() {
var trs = $('#DyanmicTable3 tr:not(:first-child):not(:nth-last-child(2)):not(:last-child)');
var trs1 = $('#DyanmicTable3 tr:last-child');
var lastTotalElement = $('#DyanmicTable3 tr:nth-last-child(2)');
console.log(trs1);
for (let i = 2; i <= 7; i++) {
const total = Array.from(trs)
.reduce((acc, tr) => x.push(Number(tr.children[i].textContent)), 0);
;
}
console.log(JSON.stringify(x));
}
this is wt i got so far getting values in an array
function GenerateTable() {
var grid = new Array();
grid.push(["Unit", "Marks", "Bloom Level"]);
var tb = $('#DyanmicTable3:eq(0) tbody ');
tb.find("tr:not(:first-child):not(:nth-last-child(2)):not(:last-child)").each(function (index, element) {
var colValtst;
$(element).find('th:not(:first-child):not(:nth-last-child(2)):not(:last-child)').each(function (index, element) {
colValtst = $(element).text();
});
$(element).find('td').each(function (index, element) {
var colVal = $(element).text();
let y = $(element).index();
if (colVal != '') {
console.log(" Value in " + colValtst + " : " + colVal.trim() + " L" + y);
//add grid here
grid.push([colValtst, colVal.trim(), "L" + y]);
}
});
});
//Build an array containing Customer records.
// $('#save').attr('href', 'AddQuestions.aspx?val1=' + grid + '');
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Get the count of columns.
var columnCount = grid[0].length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = grid[0][i];
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < grid.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < columnCount; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = grid[i][j];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
i'm building a table with pagination and sorting functionality and i'm missing something on sorting the items from all the pages.
what i want to do is to sort all items from page 1 and page 2 and not only from the current page that i'm on. can you please tell me how should i update my code to achieve that?
and i'm having another issue with the last column. how can i create a link with the href from propURL? at this moment i'm getting [object Object]
here i have a fiddle with my code
https://jsfiddle.net/c2kmruLs/2/
<div class="book-component">
<div class="table-wrapper">
</div>
</div>
var data = {
"headings": [
{
"displayName": "Book",
"columnID": "bookID"
},
{
"displayName": "Author",
"columnID": "authorID"
},
{
"displayName": "Year",
"columnID": "yearID"
},
{
"displayName": "",
"columnID": "urlID"
}
],
"items": [
{
"bookID": "The Great Gatsby",
"authorID": " F Scott Fitzgerald",
"yearID": "1925",
"urlId": {
"name": "View book",
"propURL": "https://google.com"
}
},
{
"bookID": "The Grapes of Wrath",
"authorID": "John Steinbeck",
"yearID": "1939",
"urlId": {
"name": "View book",
"propURL": "https://google.com"
}
},
{
"bookID": "A Wild Sheep Chase",
"authorID": "Haruki Murakami",
"yearID": "1982",
"urlId": {
"name": "View book",
"propURL": "https://google.com"
}
},
{
"bookID": "A Farewell to Arms",
"authorID": "Ernest Hemingway",
"yearID": "1929",
"urlId": {
"name": "View book",
"propURL": "https://google.com"
}
}
]
}
var TABLE = document.createElement('table');
TABLE.setAttribute('class', 'pagination');
TABLE.setAttribute('data-pagecount', '2');
const TABLE_WRAPPER = document.querySelector('.book-component .table-wrapper');
TABLE_WRAPPER.appendChild(TABLE);
for (const field in data) {
var tr = document.createElement('tr');
if(field == "headings"){
for (const child in data.headings) {
var th = document.createElement('th');
th.setAttribute('class', 'sort-cta');
tr.appendChild(th);
th.innerText = data.headings[child].displayName;
TABLE.appendChild(tr);
}
}
else if(field == "items"){
for (const child in data.items) {
var tr = document.createElement('tr');
let item = data.items[child];
for (const row in item) {
var td = document.createElement('td');
tr.appendChild(td);
td.innerText = item[row];
TABLE.appendChild(tr);
}
}
}
}
const SORT_LINK = document.querySelectorAll('.sort-cta');
SORT_LINK.forEach((item) => {
item.addEventListener('click', () => {
sortTable(0);
});
});
function sortTable(n) {
var table,
rows,
switching,
i,
x,
y,
shouldSwitch,
dir,
switchcount = 0;
table = document.querySelector('.pagination');
switching = true;
dir = 'asc';
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < rows.length - 1; i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName('TD')[n];
y = rows[i + 1].getElementsByTagName('TD')[n];
if (dir == 'asc') {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
} else if (dir == 'desc') {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
switchcount++;
} else {
if (switchcount == 0 && dir == 'asc') {
dir = 'desc';
switching = true;
}
}
}
}
var perPage = 20;
function genTables() {
var tables = document.querySelectorAll(".pagination");
for (var i = 0; i < tables.length; i++) {
perPage = parseInt(tables[i].dataset.pagecount);
createFooters(tables[i]);
createTableMeta(tables[i]);
loadTable(tables[i]);
}
}
function loadTable(table) {
var startIndex = 0;
if (table.querySelector('th'))
startIndex = 1;
var start = (parseInt(table.dataset.currentpage) * table.dataset.pagecount) + startIndex;
var end = start + parseInt(table.dataset.pagecount);
var rows = table.rows;
for (var x = startIndex; x < rows.length; x++) {
if (x < start || x >= end)
rows[x].classList.add("inactive");
else
rows[x].classList.remove("inactive");
}
}
function createTableMeta(table) {
table.dataset.currentpage = "0";
}
function createFooters(table) {
var hasHeader = false;
if (table.querySelector('th'))
hasHeader = true;
var rows = table.rows.length;
if (hasHeader)
rows = rows - 1;
var numPages = rows / perPage;
var pager = document.createElement("div");
if (numPages % 1 > 0)
numPages = Math.floor(numPages) + 1;
pager.className = "pager";
for (var i = 0; i < numPages ; i++) {
var page = document.createElement("div");
page.innerHTML = i + 1;
page.className = "pager-item";
page.dataset.index = i;
if (i == 0)
page.classList.add("selected");
page.addEventListener('click', function() {
var parent = this.parentNode;
var items = parent.querySelectorAll(".pager-item");
for (var x = 0; x < items.length; x++) {
items[x].classList.remove("selected");
}
this.classList.add('selected');
table.dataset.currentpage = this.dataset.index;
loadTable(table);
});
pager.appendChild(page);
}
table.parentNode.insertBefore(pager, table);
}
window.addEventListener('load', function() {
genTables();
});
For your first question: I'm not sure if that is very useful for the user, because if you sort your second page of the table you will always have the highest value in your first page of your table. And that is something you won't do I guess.
Second question: You see an [obejct object], because you want to show that object directly. You have to loop again to show the value for it.
for (const row in item) {
var td = document.createElement('td');
if (typeof(item[row]) === 'object') {
for (const obj in item[row]) {
tr.appendChild(td);
td.innerHTML = '<a target="_blank" href="' + item[row][obj] + '">' + item[row][obj] + '</a>';
TABLE.appendChild(tr);
TABLE.appendChild(tr);
}
} else {
tr.appendChild(td);
td.innerText = item[row];
TABLE.appendChild(tr);
}
}
See example below:
var data = {
"headings": [
{
"displayName": "Book",
"columnID": "bookID"
},
{
"displayName": "Author",
"columnID": "authorID"
},
{
"displayName": "Year",
"columnID": "yearID"
},
{
"displayName": "",
"columnID": "urlID"
}
],
"items": [
{
"bookID": "The Great Gatsby",
"authorID": " F Scott Fitzgerald",
"yearID": "1925",
"urlId": {
"name": "View book",
"propURL": "https://google.com"
}
},
{
"bookID": "The Grapes of Wrath",
"authorID": "John Steinbeck",
"yearID": "1939",
"urlId": {
"name": "View book",
"propURL": "https://google.com"
}
},
{
"bookID": "A Wild Sheep Chase",
"authorID": "Haruki Murakami",
"yearID": "1982",
"urlId": {
"name": "View book",
"propURL": "https://google.com"
}
},
{
"bookID": "A Farewell to Arms",
"authorID": "Ernest Hemingway",
"yearID": "1929",
"urlId": {
"name": "View book",
"propURL": "https://google.com"
}
}
]
}
var TABLE = document.createElement('table');
TABLE.setAttribute('class', 'pagination');
TABLE.setAttribute('data-pagecount', '2');
const TABLE_WRAPPER = document.querySelector('.book-component .table-wrapper');
TABLE_WRAPPER.appendChild(TABLE);
for (const field in data) {
var tr = document.createElement('tr');
if(field == "headings"){
for (const child in data.headings) {
var th = document.createElement('th');
th.setAttribute('class', 'sort-cta');
tr.appendChild(th);
th.innerText = data.headings[child].displayName;
TABLE.appendChild(tr);
}
}
else if(field == "items"){
for (const child in data.items) {
var tr = document.createElement('tr');
let item = data.items[child];
for (const row in item) {
var td = document.createElement('td');
if (typeof(item[row]) === 'object') {
for (const obj in item[row]) {
tr.appendChild(td);
td.innerHTML = '<a target="_blank" href="' + item[row][obj] + '">' + item[row][obj] + '</a>';
TABLE.appendChild(tr);
}
} else {
tr.appendChild(td);
td.innerText = item[row];
TABLE.appendChild(tr);
}
}
}
}
}
const SORT_LINK = document.querySelectorAll('.sort-cta');
SORT_LINK.forEach((item) => {
item.addEventListener('click', () => {
sortTable(0);
});
});
function sortTable(n) {
var table,
rows,
switching,
i,
x,
y,
shouldSwitch,
dir,
switchcount = 0;
table = document.querySelector('.pagination');
switching = true;
dir = 'asc';
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < rows.length - 1; i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName('TD')[n];
y = rows[i + 1].getElementsByTagName('TD')[n];
if (dir == 'asc') {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
} else if (dir == 'desc') {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
switchcount++;
} else {
if (switchcount == 0 && dir == 'asc') {
dir = 'desc';
switching = true;
}
}
}
}
var perPage = 20;
function genTables() {
var tables = document.querySelectorAll(".pagination");
for (var i = 0; i < tables.length; i++) {
perPage = parseInt(tables[i].dataset.pagecount);
createFooters(tables[i]);
createTableMeta(tables[i]);
loadTable(tables[i]);
}
}
// based on current page, only show the elements in that range
function loadTable(table) {
var startIndex = 0;
if (table.querySelector('th'))
startIndex = 1;
var start = (parseInt(table.dataset.currentpage) * table.dataset.pagecount) + startIndex;
var end = start + parseInt(table.dataset.pagecount);
var rows = table.rows;
for (var x = startIndex; x < rows.length; x++) {
if (x < start || x >= end)
rows[x].classList.add("inactive");
else
rows[x].classList.remove("inactive");
}
}
function createTableMeta(table) {
table.dataset.currentpage = "0";
}
function createFooters(table) {
var hasHeader = false;
if (table.querySelector('th'))
hasHeader = true;
var rows = table.rows.length;
if (hasHeader)
rows = rows - 1;
var numPages = rows / perPage;
var pager = document.createElement("div");
// add an extra page, if we're
if (numPages % 1 > 0)
numPages = Math.floor(numPages) + 1;
pager.className = "pager";
for (var i = 0; i < numPages ; i++) {
var page = document.createElement("div");
page.innerHTML = i + 1;
page.className = "pager-item";
page.dataset.index = i;
if (i == 0)
page.classList.add("selected");
page.addEventListener('click', function() {
var parent = this.parentNode;
var items = parent.querySelectorAll(".pager-item");
for (var x = 0; x < items.length; x++) {
items[x].classList.remove("selected");
}
this.classList.add('selected');
table.dataset.currentpage = this.dataset.index;
loadTable(table);
});
pager.appendChild(page);
}
// insert page at the top of the table
table.parentNode.insertBefore(pager, table);
}
window.addEventListener('load', function() {
genTables();
});
tr.inactive {
display: none;
}
.table-wrapper {
display: flex;
flex-direction: column-reverse;
}
.pager {
display: flex;
justify-content: center;
padding: 0;
margin-top: 10px;
font-weight: 800;
}
.pager-item.selected {
outline: none;
border-color: #0077cc;
background: #0077cc;
color: #fff;
cursor: default;
}
<div class="book-component">
<div class="table-wrapper">
</div>
</div>
I'm creating a function that should take the data from an array (results) and put them into specific columns of the table. The array is divided with numbers that identify the column in which the following data should be entered.
Eg:
var results = [1, 'aaaaaa', 'bbb',2, 'ccc', 3, 'dddd', 'eeee', 4, 'fff'];
col 1: 'aaaaaa', 'bbb';
col 2: 'ccc'; etc.
I've tried it in many ways and I can not get it to work.
At the moment the code looks like this. I'm no sure how to do it:
var results = [1, 'aaaaaa','bbb',2, 'ccc', 3, 'dddd', 'eeee', 4, 'fff'];
var k = 0;
function populateTable(table, rows, cells, content) {
if (!table) table = document.createElement('table');
for (var i = 0; i < rows; ++i) {
var row = document.createElement('tr');
for (var j = 0; j < cells; ++j) {
row.appendChild(document.createElement('td'));
if (i > 0 && j == 0) {
row.cells[j].appendChild(document.createTextNode(content + 'PN'));
}
else if (i == 0 && j == 0) {
row.cells[j].appendChild(document.createTextNode(content + 'TYPE'));
}
else if (j > 0 && i == 0) {
row.cells[j].appendChild(document.createTextNode(content + 'LABLE ' + j));
}
else if (j > 0 && i > 0 && results[i] != k) {
row.cells[k].appendChild(document.createTextNode(content + results[i]));
}
}
table.appendChild(row);
k++;
}
return table;
}
function load() {
document.getElementById('tablearea')
.appendChild(populateTable(null, 9, 10, ""));
}
First format the results into something like:
{
1: ['aaaaaa', 'bbb'],
2: ['ccc'],
3: ['dddd', 'eeee'],
4: ['fff']
}
Then generate the table:
const results = [1, 'aaaaaa', 'bbb',2, 'ccc', 3, 'dddd', 'eeee', 4, 'fff', 5, 'ggg', 'hhhh', 'iiii'];
// First format the results
const formattedResults = {};
let columnIndex = 0;
results.forEach(elt => {
if (!isNaN(elt)) {
formattedResults[elt] = [];
columnIndex = elt;
} else {
formattedResults[columnIndex].push(elt);
}
});
// Then generate the table
const table = document.createElement('table');
const columnKeys = Object.keys(formattedResults);
const maxRows = Math.max(...columnKeys.map(key => formattedResults[key].length));
for (let i = 0; i < maxRows; i = i + 1) {
const tr = document.createElement('tr');
columnKeys.forEach(colKey => {
const td = document.createElement('td');
if (formattedResults[colKey][i] !== undefined) {
td.textContent = formattedResults[colKey][i];
tr.appendChild(td);
}
});
table.appendChild(tr);
}
document.getElementById('tableArea').appendChild(table);
<div id="tableArea"></div>
I have created a table.
I have text input where I type some text. It refers to some element with special values.
When I click a button the productname is added to the table (using insertCell()).
I want to give a unique id to every new table element.
function add1() {
var row, cell;
var productname = document.getElementById("produkt1").value; // text input
var table = document.getElementById("pos1"); // button near text input
if(productname === "Egg") {
p = ["Egg", "", 20, 10, 11, 101];
}
if(productname === "Milk") {
p = ["Milk", "", 30, 5, 12, 75];
}
row = table.insertRow(2);
var c_id = 0;
for (var i = 0; i < p.length ; i++) {
cell = row.insertCell(i);
cell.innerHTML = p[i];
for (var j = 0; j < 1 ; j++) {
cell.id = 'tdp1' + k_id;
c_id++;
}
} // It only works for one element, and the others have the same id as elements from row1
}
a. There seems to be a type in the line cell.id = 'tdp1' + k_id; It is supposed to be c_id instead of k_id
b. You do not need the second for loop for anything and just can remove it.
The following code gives me a new row with ids for each cell (tdp10 to tdp15)
function add1() {
var row, cell;
var productname = document.getElementById("produkt1").value; // text input
var table = document.getElementById("pos1"); // button near text input
if(productname === "Egg") {
p = ["Egg", "", 20, 10, 11, 101];
}
if(productname === "Milk") {
p = ["Milk", "", 30, 5, 12, 75];
}
row = table.insertRow(2);
var c_id = 0;
for(var i = 0; i < p.length ; i++){
cell = row.insertCell(i);
cell.innerHTML = p[i];
cell.id = 'tdp1' + c_id;
c_id++;
}
}
I found solution:
function add1() {
var row, cell;
var productname = document.getElementById("produkt1").value;
var table = document.getElementById("pos1");
if(productname === "Egg") {
p = ["Egg", "", 20, 10, 11, 101];
}
if(productname === "Milk") {
p = ["Milk", "", 30, 5, 12, 75];
}
var cells = document.getElementsByClassName("pos");
row = table.insertRow(2);
for(var i = 0; i < p.length ; i++){
cell = row.insertCell(i);
cell.innerHTML = p[i];
cell.className = "pos";
for(var j = 0; j < cells.length ; j++){
cell.id = 'tdp1' + j;
}
}
I gave created cell a className. It's working, but thank you for help. :)
I have to populate a table using JSON and Javascript but the data go to next row. Whereas I wish to have data just below the row of column header
Here is my json:
var myList = [{ "Column1": "abc" },
{ "Column2": "25" },
{ "Column3": "xyz" }];
The given code fills the data in this sequence :
column1 column2 column3
abc
25
xyz
But I wish to have it like :
column1 column2 column3
abc 25 xyz
Here is my code:
var myList = [{ "Column1": "abc" },
{ "Column2": "25" },
{ "Column3": "xyz" }];
$(document).ready(function ()
{
buildHtmlTable();
});
function buildHtmlTable()
{
var columns = addAllColumnHeaders(myList); // columns get the name of coluns
alert("test : " + myList);
for (var i = 0 ; i < myList.length ; i++)
{
var row$ = $('<tr/>');
for (var colIndex = 0 ; colIndex < columns.length ; colIndex++)
{
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
row$.append($('<td/>').html(cellValue));
}
$("#excelDataTable").append(row$);
}
}
Edit
function addAllColumnHeaders(myList)
{
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0 ; i < myList.length ; i++)
{
var rowHash = myList[i];
for (var key in rowHash)
{
if ($.inArray(key, columnSet) == -1)
{
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#excelDataTable").append(headerTr$);
return columnSet;
}
and
<table id="excelDataTable" class="contentpanel" border="1"></table>
Take var row$ = $('<tr/>'); out of the loop. No need for double loop. Try this:
var myList = [{ "Column1": "abc" },
{ "Column2": "25" },
{ "Column3": "xyz" }];
$(document).ready(function ()
{
buildHtmlTable();
});
function buildHtmlTable()
{
var columns = addAllColumnHeaders(myList); // columns get the name of coluns
//alert("test : " + myList);
var row$ = $('<tr/>');
var colIndex = 0;
for (var i = 0 ; i < myList.length ; i++)
{
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
row$.append($('<td/>').html(cellValue));
$("#excelDataTable").append(row$);
colIndex++;
}
}
function addAllColumnHeaders(myList)
{
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0 ; i < myList.length ; i++)
{
var rowHash = myList[i];
for (var key in rowHash)
{
if ($.inArray(key, columnSet) == -1)
{
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#excelDataTable").append(headerTr$);
return columnSet;
}