Looping through HTML table with Javascript/jQuery - javascript

I am struggling to figure out how to loop through a table in HTML.
I have a 2D Javascript object that I would like to populate cells with index i,j from myObject[i][j]. I have a basic html table template but with blank <td></td> tags. I have looked at ways to do it in jQuery and Javascript, but to no avail.
Edit: Here's my code:
var table = document.getElementById("myTable");
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
col = myObject[i][j]
}
}
My HTML is just a standard table eg.:
<table id="myTable">
<thead>
<tr>
<th></th>
</tr>
<tr>
<td></td>
</tr>
</thead>
<tbody>
<tr>
<th></th>
<td></td>
</tbody>
</table>
Any help would be greatly appreciated.

Thanks #bulicmatko
You can try something like this: jsfiddle.net/pt9go1s6

You can try something like this:
HTML:
<div id="tableWrap"></div>
JS:
var tableWrap = document.getElementById("tableWrap");
var data = [
['First Name', 'Last Name', 'Age'],
['Johnny', 'Bravo', '27'],
['Bugs', 'Bunny', '35'],
['Mickey', 'Mouse', '35'],
];
var table = "<table>";
for (var i = 0; i < data.length; i++) {
table += "<tr>";
for (var j = 0; j < data[i].length; j++) {
table += "<td>" + data[i][j] + "<td>";
}
table += "</tr>";
}
table += "</table>";
tableWrap.innerHTML = table;
Here is the demo.
Hope it helps ;)

A jQuery solution could be use child related selectors to filter relevant cells.
var ar = [
['A', 'B'],
['C', 'D']
];
for (var r = 0; r < 2; ++r) {
for (var c = 0; c < 2; ++c) {
$('table tr:nth-of-type(' + (r + 1) + ') td:nth-of-type(' + (c + 1) + ')').text(ar[r][c]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>.</td>
<td>.</td>
</tr>
<tr>
<td>.</td>
<td>.</td>
</tr>
</table>

Related

Inserting table data under a particular table header from an Object

Given a Javscript Object:
var obj = {
"results": [{
"B": "Row 1 Col 2"
}, {
"A": "Row 1 Col 1"
"B": "Row 2 Col 2"
}, {
"C": "Row 1 Coll 3"
}
}]
I wish to convert it to a table that looks like the following.
<table border="1">
<thead>
<tr>
<th id="A">A</th>
<th id="B">B</th>
<th id="C">C</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 Col 1</td>
<td>Row 1 Col 2</td>
<td>Row 1 Col 3</td>
</tr>
<tr>
<td></td>
<td>Row 2 Col 2</td>
<td></td>
</tr>
</tbody>
</table>
Which looks like:
Demo Table Data
More precisely, I'm looking for a way to somehow insert the value of a property directly below it.
javascript:
var cols = obj.results.reduce(function(arr, currObj) {
return arr.concat(Object.keys(currObj).filter(function(key) {
return arr.indexOf(key) == -1
}));
}, []).sort();
// create header from sorted column keys
var header = '<tr><th>' + cols.join('</th><th>') + '</th></tr>';
var rows = obj.results.map(function(item) {
// loop over column keys checking matches to item keys
return '<tr>' +
cols.map(function(key) {
return '<td>' + (item.hasOwnProperty(key) ? item[key] : '') + '</td>';
}).join('') + '</tr>';
}).join('');
var table = '<table border="1">' + header + rows + '</table>';
Might not be the most elegant way but works
var cols = obj.results.reduce(function(arr, currObj) {
return arr.concat(Object.keys(currObj).filter(function(key) {
return arr.indexOf(key) == -1
}));
}, []).sort();
// create header from sorted column keys
var header = '\n<thead>\n\t<tr>\n\t\t<th>' + cols.join('</th>\n\t\t<th>') + '</th>\n\t</tr>\n</thead>';
var j = {}
obj.results.map(function(item) {
// loop over column keys checking matches to item keys
cols.map(function(key) {
if(j[key] == undefined)
{
j[key] = []
}
if (item.hasOwnProperty(key))
{
j[key].push(item[key]);
}
})
});
var rows = []
var index = 0
for(let k in j)
{
rows.push([])
for(let e in j[k])
{
rows[index].push(j[k][e])
}
index += 1
}
function transposeArray(array, arrayLength){
var newArray = [];
for(var i = 0; i < array.length; i++){
newArray.push([]);
};
for(var i = 0; i < array.length; i++){
for(var j = 0; j < arrayLength; j++){
newArray[j].push(array[i][j]);
};
};
return newArray;
}
rows = transposeArray(rows, 3)
var rowsStr = "";
for(let k in rows)
{
rowsStr += '\n\t<tr>';
for(let e in rows[k])
{
if(rows[k][e] != undefined)
{
rowsStr += '\n\t\t<td>' + rows[k][e]+ '\t\t</td>'
}
else
{
rowsStr += "\n\t\t<td></td>"
}
}
rowsStr += '\n\t</tr>';
}
var table = '<table border="1">' + header + "\n<tbody>" + rowsStr + "\n</tbody>" + '\n</table>';

HTML table not showing table header

I have an html table with 3 columns and any number of rows (based on a database output.)
var fields = ['a','b','c']; //variable from database
var data = ['p', 'q', 'r']; //variable from database
var who = ['x', 'y', 'z']; //variable from database
$(function() {
var table = $("#resultTable");
var rowNum = 3;
var resultHtml = '';
for(var i = 0 ; i < rowNum ; i++) {
resultHtml += ["<tr>",
"<td>",
fields[i],
"</td>",
"<td>",
data[i],
"</td>",
"<td>",
who[i],
"</td>",
'</tr>'].join("\n");
}
table.html(resultHtml);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="resultTable">
<tr>
<th>Question</th>
<th>Decision</th>
<th>Whose Decision</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
The table shows the content properly but doesn't show the headers of each of the column such as Question, Decision, Whose Decision
What am I missing?
You replaced whole html.
You need to apped html like
table.append(resultHtml);
By using table.html(...) you override the entire content of your table (include the header).
You can use something like that:
var fields = ['a','b','c']; //variable from database
var data = ['p', 'q', 'r']; //variable from database
var who = ['x', 'y', 'z']; //variable from database
$(function() {
var table = $("#resultTable");
var rowNum = 3;
var resultHtml = $('<table>').append(table.find('tr').first()).html();
for(var i = 0 ; i < rowNum ; i++) {
resultHtml += ["<tr>",
"<td>",
fields[i],
"</td>",
"<td>",
data[i],
"</td>",
"<td>",
who[i],
"</td>",
'</tr>'].join("\n");
}
table.html(resultHtml);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="resultTable">
<tr>
<th>Question</th>
<th>Decision</th>
<th>Whose Decision</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Because you use resultHtml to replace table HTML code.
You are overwriting the table in the javascript from what I can see. table.html(resultHtml) is replacing what you have in the html code.

jQuery recursive find

<table id="TemplateBindVarsTable" class="table">
<tr>
<td class="control-label">${MeetingName}</td>
<td class="form-control" style="border:0"><input id="${MeetingName}"
type="text"></td>
</tr>
<tr>
<td class="control-label">${MeetingLocation}</td>
<td class="form-control" style="border:0"><input id="${MeetingLocation}"
type="text"></td>
</tr>
</table>
I have the following jQuery code that goes against this:
function processTemplate() {
var rows = $('#TemplateBindVarsTable').find("tr");
for (var i = 0; i < rows.length; i++) {
// NONE OF THESE WORK
var cells = rows[i].children();
var key = rows[i].find("td.control-label").text();
var val = rows[i].find("td.control-label>input").val();
alert('key: ' + key + ", val: " + val);
}
}
What am I missing? Shouldn't I be able to get rows back and then run a find/children on them?!
You just need to modify it a little like following to convert DOM object to jQuery object on which you can execute jQuery's methods like .children() and .find():
function processTemplate() {
var rows = $('#TemplateBindVarsTable').find("tr");
for (var i = 0; i < rows.length; i++) {
// NONE OF THESE WORK
var cells = $(rows[i]).children();
var key = $(rows[i]).find("td.control-label").text();
var val = $(rows[i]).find("td.control-label>input").val();
alert('key: ' + key + ", val: " + val);
}
}

Unable to retieve the particular value of cell on table using javascript

I am using the following code to retrieve the values of a particular cell of a table.:
function addCatAttr()
{
var tbl = document.getElementById("tblAttributes1");
if (tbl.rows.length > 1)
{
for ( var i = 1 ; i < tbl.rows.length ; i++ )
{
var r = tbl.rows[i];
var catname1 =r.cells[0].document.getElementsByTagName("input").item(1).value;
var lifecycycleattr1 = r.cells[0].document.getElementsByTagName("input").item(2).value;
var stateattr1 = r.cells[0].document.getElementsByTagName("input").item(3).value;
}
}
}
and my html code is :
<table id="tblAttributes1">
<tr>
<td>Category</td>
<td>Life Cycle Attribute</td>
<td>State Attribute</td>
</tr>
<tr>
<td>cat1</td>
<td>pf</td>
<td>state</td>
</tr>
</table>
I want to retrieve each value of a particular.
Its just an example.I have more thane two rows for which i need for loop to get the values of each cell.
See if this points you in the right direction:
function addCatAttr()
{
var tbl = document.getElementById("tblAttributes1");
if (tbl.rows.length > 1)
{
for ( var i = 1 ; i < tbl.rows.length ; i++ )
{
var r = tbl.rows[i];
var catname1 =r.cells[0].innerText;
var lifecycycleattr1 = r.cells[1].innerText;
var stateattr1 = r.cells[2].innerText;
alert('catname1: ' + catname1 + '\r\n' +
'lifecycycleattr1: ' + lifecycycleattr1 + '\r\n' +
'stateattr1: ' + stateattr1 + '\r\n');
}
}
}
<table id="tblAttributes1">
<tr>
<td>Category</td>
<td>Life Cycle Attribute</td>
<td>State Attribute</td>
</tr>
<tr>
<td>cat1</td>
<td>pf</td>
<td>state</td>
</tr>
</table>
<input type="button" onclick="addCatAttr()" value="Click me" />
This can help better...
function addCatAttr()
{
var tbl = document.getElementById("tblAttributes1");
if (tbl.rows.length > 1)
{
for ( var i = 1 ; i < tbl.rows.length ; i++ )
{
var r = tbl.rows[i];
var catname1 =r.cells[0].innerHTML;
var lifecycycleattr1 = r.cells[1].innerHTML;
var stateattr1 = r.cells[2].innerHTML;
alert('catname1: ' + catname1 + '\r\n' +
'lifecycycleattr1: ' + lifecycycleattr1 + '\r\n' +
'stateattr1: ' + stateattr1 + '\r\n');
}
}
}
<table id="tblAttributes1">
<tr>
<td>Category</td>
<td>Life Cycle Attribute</td>
<td>State Attribute</td>
</tr>
<tr>
<td>cat1</td>
<td>pf</td>
<td>state</td>
</tr>
</table>
<input type="button" onclick="addCatAttr()" value="Click me" />
You need to apply two for loops one for table length and the other for the each td in tr. This is the code.
var table = document.getElementById('tblAttributes1'),
rows = table.getElementsByTagName('tr');
for (var i = 0; i< rows.length; i++) {
var tds = rows[i].getElementsByTagName('td');
for(var x=0;x<tds.length;x++){
console.log(tds[x].innerHTML);
}
And the fiddle is-
http://jsfiddle.net/09q6n3m2/16/

Export HTML visible table column content to client side, 2010 Excel page

With F12 debug, the JQuery codes is able to skip hidden column cell, only exort cells not hidden, but the >last statement, window.open NOT able to bring it up on the 2010 EXCEL page.
The following code has been simplied to focus the problem, not able to export HTML table to 2010 Execel
<body>
<table id="myGrid">
<tr><th style="display:">First Column</th>
<th style="display:">Second Column</th>
<th style="display:">Third Column</th>
<th style="display: none">Forth Column</th>
</tr>
<tr><td> 2</td><td> two</td><td> deux</td><td style="display: none"> zwei</td></tr>
<tr><td> 3</td><td> three</td><td> trois</td><td style="display: none"> drei</td></tr>
<tr><td> 4</td><td> four</td><td>quattre</td><td style="display: none"> vier</td></tr>
<tr><td> 5</td><td> five</td><td> cinq</td><td style="display: none">fünf</td></tr>
<tr><td> 6</td><td> six</td><td> six</td><td style="display: none"> sechs</td></tr>
</table>
<br />
Test: <input id="ExportExcel" type='submit' value='Export Excel'>
<script type="text/javascript">
$(document).ready(function () {
$('#ExportExcel').click(function () {
var html;
var numofRows;
var gTable = document.getElementById('myGrid');
numofRows = gTable.rows.length - 1;
var numofCells;
var trhtml = "";
numofCells = gTable.rows[0].cells.length - 1;
for (r = 0; r <= numofRows; r++) {
var c = 0;
var tdhtml = "";
for (c = 0; c <= numofCells; c++) {
if (!(gTable.rows[r].cells[c].currentStyle.display == "none")) {
var tempstr = gTable.rows[r].cells[c].innerText;
tdhtml = tdhtml + "<td>" + gTable.rows[r].cells[c].innerText + "</td>";
}
}
trhtml = trhtml + "<tr>" + tdhtml + "</tr>";
}
html = "<table border='1'>" + trhtml + "</table>";
// MS OFFICE 2003 : data:application/vnd.ms-excel
// MS OFFICE 2007 : application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
window.open('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,' + encodeURIComponent(html));
});
});
</script>
</body>
Ans For the above question:
Here i added class to hidden td
<table id="myGrid">
<tr><th style="display:">First Column</th>
<th style="display:">Second Column</th>
<th style="display:">Third Column</th>
<th style="display: none">Forth Column</th>
</tr>
<tr><td> 2</td><td> two</td><td> deux</td><td class="xyz" style="display: none"> zwei</td></tr>
<tr><td> 3</td><td> three</td><td> trois</td><td class="xyz" style="display: none"> drei</td></tr>
<tr><td> 4</td><td> four</td><td>quattre</td><td class="xyz" style="display: none"> vier</td></tr>
<tr><td> 5</td><td> five</td><td> cinq</td><td class="xyz" style="display: none">fünf</td></tr>
<tr><td> 6</td><td> six</td><td> six</td><td class="xyz" style="display: none"> sechs</td></tr>
</table>
when click on export add this statement -> $('.xyz').remove();
like this
$('#ExportExcel').click(function () {
$('.xyz').remove();
// add export statements here
});
it will work
After export, the class xyz related td's are not displaying in your excel.
The attached JQuery codes will export visible column header, and row cell content to client side Excel ; just copy and paste the following codes to become part of Javascript codes (insert into question codes), and change button id to ExportExcel2. NOTE: assumption: client has Excel installed.
$('#ExportExcel2').click(function () {
str = "";
var myTable = document.getElementById('myGrid');
var rows = myTable.getElementsByTagName('tr');
var rowCount = myTable.rows.length;
var colCount = myTable.getElementsByTagName("tr")[0].getElementsByTagName("th").length;
var ExcelApp = new ActiveXObject("Excel.Application");
var ExcelWorkbook = ExcelApp.Workbooks.Add();
var ExcelSheet = ExcelWorkbook.ActiveSheet; //new ActiveXObject("Excel.Sheet");
//ExcelSheet.Application.Visible = true;
ExcelApp.Visible = true;
ExcelSheet.Range("A1", "Z1").Font.Bold = true;
ExcelSheet.Range("A1", "Z1").Font.ColorIndex = 23;
//Format table headers
var tarcol = 0;
for (var i = 0; i < 1; i++) {
targetCol = 1;
for (var j = 0; j < colCount; j++) {
if (!(myTable.getElementsByTagName("tr")[i].getElementsByTagName("th")[j].currentStyle.display == "none")) {
str = myTable.getElementsByTagName("tr")[i].getElementsByTagName("th")[j].innerHTML;
//ExcelSheet.Cells(i + 1, j + 1).Value = str;
ExcelSheet.Cells(i + 1, targetCol).Value = str;
targetCol += 1;
}
}
ExcelSheet.Range("A1", "BD1").EntireColumn.AutoFit();
}
for (var i = 1; i < rowCount; i++) {
targetCol = 1;
for (var k = 0; k < colCount; k++) {
if (!(myTable.getElementsByTagName("tr")[i].getElementsByTagName("td")[k].currentStyle.display == "none")) {
str = rows[i].getElementsByTagName('td')[k].innerHTML;
//ExcelSheet.Cells(i + 1, k + 1).Value = myTable.rows[i].cells[k].innerText;
ExcelSheet.Cells(i + 1, targetCol).Value = myTable.rows[i].cells[k].innerText;
targetCol += 1;
}
}
ExcelSheet.Range("A" + i, "Z" + i).WrapText = true;
ExcelSheet.Range("A" + 1, "Z" + i).EntireColumn.AutoFit();
}
//ExcelSheet.SaveAs("C:\\TEST.XLS");
//ExcelSheet.Application.Quit();
});

Categories

Resources