I am new to Javascript/jQuery and I need some help adding a header to my table. I am getting my data from a JSON array. Here is the code I currently have.
function jsonTable (ChartNum, divclass) {
"use strict";
var output = JSON.parse(document.getElementById(ChartNum).innerHTML);
var table = $('<table></table>');
for (var i=0; i < output.length; i++) {
var tr = $('<tr></tr>');
for (var key in output[i]) {
var td = $('<td></td>');
td.attr('class', key);
td.text(output[i][key]);
tr.append(td);
}
table.append(tr);
}
$(divclass).append(table);
}
jsonTable( 'pdfChart1', '#pdfTable1');
Any help would be really appreciated. Thanks,
Try this:
function jsonTable (ChartNum, divclass) {"use strict";
var output = JSON.parse(document.getElementById(ChartNum).innerHTML);
var table = $('<table></table>');
var trHeader = $('var table = $('<tr><th>Column1</th><th>Column2</th> <th>ColumnsN</th></tr>');
table.append(trHeader);
for (var i=0; i < output.length; i++) {
var tr = $('<tr></tr>');
for (var key in output[i]) {
var td = $('<td></td>');
td.attr('class', key);
td.text(output[i][key]);
tr.append(td);
}
table.append(tr);
}
$(divclass).append(table);
}
jsonTable( 'pdfChart1', '#pdfTable1');
I added variable trHeader where you can add the name of your columns, of course this will only work if your columns are always the same. Or you can get another json with the names of columns and iterate over it to build trHeader in a similar way you build the tds.
Related
I am building a historical dash (currently with fake data due to security) and I have the multi select list that gens the first name of the person in alphabetic order. Now when selecting one name it regens the table with said name. When I select multiple names, it regens the table with the "lowest" alphabetical name. I cant figure out why my filter function is not building the new array with all selected names that are true in the "selected" statement. However I used the push() function and that works but only shows the first name. Any help would be awesome, I am new to JS and working with DOM is really fun!
histData is the main array with all info,
fNameArr is the re populated array from the filter method given the multi selections
Here is my js:
function mSelList(){
var selName = document.getElementById("jomax");
var fNameArr;
for(i=0; i<selName.length;i++){
let currentName = selName[i];
if(currentName.selected == true){
let fName = currentName.value;
fNameArr = histData.filter(function(data){
return data.first_name == fName;
});
}
}
function createTable(){
var col = [];
for (var i = 0; i < fNameArr.length; i++) {
for (var key in fNameArr[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// create table section with css filters
var table = document.createElement("table");
table.setAttribute("class", "table is-hoverable is-bordered is-narrow");
table.setAttribute("id", "table");
var tr = table.insertRow(-1);
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.setAttribute("class", "is-uppercase is-size-7"); // attributes
th.innerHTML = col[i];
tr.appendChild(th);
}
for (var i = 0; i < fNameArr.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = fNameArr[i][col[j]];
}
}
var tblSec = document.getElementById("tableSec");
tblSec.innerHTML = "";
tblSec.appendChild(table);
}
createTable();
}
You are using getElementById and running a loop over it? getElementById will return one specific element not a list of element. Here is mdn_link for more info.
var selName = document.getElementById("jomax");
I would suggest to use class instead.
I am trying get data from a json file using $.getJSON. However, the code only works on Edge browser but not any other bowers and I have no idea at all. Please see the code below:
function CreateTableFromJSON(){
$(document).ready(function () {
$.getJSON("wellness.json", function (data) {
var cars = new Array("Athlete", "Muscle-Soreness", "Sleep-Quality");
var arrItems = []; // THE ARRAY TO STORE JSON ITEMS.
$.each(data, function (index, value) {
arrItems.push(value);
});
// EXTRACT VALUE FOR TABLE HEADER.
var col = [];
for (var i = 0; i < arrItems.length; i++) {
for (var key in arrItems[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < arrItems.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = cars[i];
tr.appendChild(th);
}
for (var i = 0; i < col.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < arrItems.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = arrItems[j][col[i]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
});
});
}
Hi guys, I am trying get data from a json file using $.getJSON. However, the code only works on Edge browser but not any other bowers and I have no idea at all.
Below is the JavaScript functionalities addRow() I have used to add the rows dynamically and now am trying to highlight the selected row with red color using rowhighlight() function.
/Function to addRows dynamically to the HTML table/
function addRow(msg)
{
var table = document.getElementById("NotesFinancialSummary");
var finSumArr1 = msg.split("^");
var length = finSumArr1.length-1;
alert("length"+ length);
for(var i=1; i<finSumArr1.length; i++)
{
var rowValues1 = finSumArr1[i].split("|");
tb=document.createElement("tbody");
var tbody=document.createElement("tbody");
table.appendChild(tbody);
var tr=document.createElement("tr");
tbody.appendChild(tr);
for(var k=0;k<=10;k++)//adding data to table dynamically
{
var td=document.createElement("td");
tr.appendChild(td);
var element1=rowValues1[k];
td.innerHTML =element1;
tr.onclick=function(){
rowhighlight(this);//calling the rowhighlight function
}
}
}
}
function rowhighlight(x)
{
var index = x.rowIndex;
document.getElementById("NotesFinancialSummary").rows [index].style.backgroundColor = "red";
}
One approach is to first loop through the other rows and remove the styling (really should be a class) then apply the styling (again, class) to the selected row.
Here's one way of doing it:
function rowHighlight() {
var selectedRows = document.getElementsByClassName('selected');
for (var n = 0; n < selectedRows.length; n++) {
selectedRows[n].className = '';
}
this.className = 'selected'
}
And here's a working example of it, though very simple: fiddle time!
I have the following javascript that adds a new row to the bottom of a table.
It works fine in Firefox, but it doesn't work in IE (version 8).
There are no visible errors, as far as I can tell.
Any ideas are very helpful!
function addRow() {
// locate the last row in the table
var table = document.getElementById("approversTable");
var rows = document.getElementsByTagName("tr");
var rowToClone;
for (var i=0; i<rows.length; i++) {
if (rows[i].id != "") {
rowToClone = rows[i];
}
}
// clone the row
var clone = rowToClone.cloneNode(true);
var rowId = Math.floor(Math.random()*100000);
clone.id = rowId;
// add the new row to the table
table.appendChild(clone);
}
You should select the table tbody element instead of the table directly.
function addRow() {
var table = document.getElementById("approversTable");
var tbody = table.tbodies[0];
var rows = document.getElementsByTagName("tr");
var rowToClone;
for (var i=0; i<rows.length; i++) {
if (rows[i].id != "") {
rowToClone = rows[i];
}
}
// clone the row
var clone = rowToClone.cloneNode(true);
var rowId = Math.floor(Math.random()*100000);
clone.id = rowId;
// add the new row to the table
tbody.appendChild(clone);
}
more info at: http://www.w3schools.com/jsref/coll_table_tbodies.asp
Is there an easy way to combine rows in an HTML table where the first column is the same? I basically have a table set up like:
<table>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test2</td><td>12345</td><td>12345</td><tr>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test2</td><td>12345</td><td>12345</td><tr>
</table>
and I want it to generate:
<table>
<tr><td>test</td><td>37035</td><td>37035</td><tr>
<tr><td>test2</td><td>24690</td><td>24690</td><tr>
</table>
using jQuery:
var map = {};
$('table tr').each(function(){
var $tr = $(this),
cells = $tr.find('td'),
mapTxt = cells.eq(0).text();
if(!map[mapTxt]){
map[mapTxt] = cells;
} else {
for(var i=1, l=cells.length; i<l; i++){
var cell = map[mapTxt].eq(i);
cell.text(parseInt(cell.text()) + parseInt(cells[i].text()));
}
$tr.remove();
}
});
this is a "dumb" script -- no error handling for cases like different number of cells, fields being non-numeric, etc. Add those if necessary.
Also, depending on how it's generated, it's better to do this server-side.
Here's a plain JavaScript version.
window.onload = function() {
var table = document.getElementById('mytable');
var tr = table.getElementsByTagName('tr');
var combined = Array();
for (i = 0; i < tr.length; i++) {
var td = tr[i].getElementsByTagName('td');
var key = td[0].innerText;
if (!combined[key]) {//if not initialised
combined[key] = Array();
for (j = 0; j < td.length - 1; j++) combined[key][j] = 0;
}
for (j = 0; j < td.length - 1; j++)
combined[key][j] += parseInt(td[j + 1].innerText);
}
while (table.hasChildNodes()) table.removeChild(table.lastChild);
var tbody = document.createElement('tbody');//needed for IE
table.appendChild(tbody);
for (var i in combined) {
tr = document.createElement('tr');
tbody.appendChild(tr);
td = document.createElement('td');
td.innerText = i;
tr.appendChild(td);
for (j = 0; j < combined[i].length; j++) {
td = document.createElement('td');
td.innerText = combined[i][j];
tr.appendChild(td);
}
}
}
This will work on tables with any number of rows and any number of cells. I suppose you want to make the sum for every column, that's what this script does.
And as cwolves mentioned, it is more logical to do this serverside. Users that have JS disabled will see the not so clean uncombined table.