jQuery recursive find - javascript

<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);
}
}

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>';

jQuery sum the values of table rows

hello i have this table
i want to get the total of each row in the total column
jQuery
//Monthly Marketing Cost Report
$.get('/dashboard/costs', function(data){
$.each(data,function(i,value){
var leads = $('#leads');
var budget_total_year = $('#full_year_cost');
var budget_total_month = $('#share_cost');
var budget_per_lead = $('#cost_per_lead');
leads.append('<th>' + value.olxTotal + '</th>');
budget_total_year.append('<th>' + value.budget_total_year + '</th>');
budget_total_month.append('<th>' + value.budget_total_month + '</th>');
budget_per_lead.append('<th>' + value.budget_per_lead + '</th>');
})
})
HTML
<tbody id="tableData-marketMonth">
<tr id="leads">
<th>Leads</th>
</tr>
<tr id="full_year_cost">
<th>Full Year Cost</th>
</tr>
<tr id="share_cost">
<th>{{date('F')}} Share of Cost</th>
</tr>
<tr id="cost_per_lead">
<th>Cost per Lead</th>
</tr>
</tbody>
i was going to calculate the total through php but i though it can be easier
using jQuery just putting the sum of each row at the end
Thank you very much
Create variables before the loop. add to the variables in the loop and then assign the sum at the end.
$.get('/dashboard/costs', function(data){
var sumLeads = 0;
var sumFullYearCost = 0;
var sumShareCost = 0;
var sumCostPerLead = 0;
var tr_leads = $('#leads');
var tr_budget_total_year = $('#full_year_cost');
var tr_budget_total_month = $('#share_cost');
var tr_budget_per_lead = $('#cost_per_lead');
$.each(data,function(i,value){
tr_leads.append('<th>' + value.olxTotal + '</th>');
tr_budget_total_year.append('<th>' + value.budget_total_year + '</th>');
tr_budget_total_month.append('<th>' + value.budget_total_month + '</th>');
tr_budget_per_lead.append('<th>' + value.budget_per_lead + '</th>');
sumLeads += value.olxTotal;
sumFullYearCost += value.budget_total_year;
sumShareCost += value.budget_total_month;
sumCostPerLead += value.budget_per_lead;
});
tr_leads.append('<th>' + sumLeads + '</th>');
tr_budget_total_year.append('<th>' + sumFullYearCost + '</th>');
tr_budget_total_month.append('<th>' + sumShareCost + '</th>');
tr_budget_per_lead.append('<th>' + sumCostPerLead + '</th>');
});
Example for leads row using Array.map and Array.reduce. Use jQuery to get the td elements.
var leads = $('#leads');
const total = leads.children('td').toArray().map(x=>Number(x.innerHTML)).reduce((sum, x) => sum + x)
leads.append(`<th>${total}</th>`);
Try something like this.
$('#tableData-marketMonth tr').each(function () {
var row = $(this);
var rowTotal = 0;
$(this).find('th').each(function () {
var th = $(this);
if ($.isNumeric(th.text())) {
rowTotal += parseFloat(th.text());
}
});
row.find('th:last').text(rowTotal);
});
NOTE: change 'th' to 'td' if you have td's. Looking at your jquery, it looks like you are appending th's.
You can use my written code to vote if you like it...
HTML
<table>
<thead>
<tr>
<th>MAX ATK</th>
<th>MAX DEF</th>
<th>MAX HP</th>
<th>Overall</th>
</tr>
</thead>
<tbody>
<tr>
<td class="combat">8170</td>
<td class="combat">6504</td>
<td class="combat">6050</td>
<td class="total-combat"></td>
</tr>
<tr>
<td class="combat">8500</td>
<td class="combat">10200</td>
<td class="combat">7650</td>
<td class="total-combat"></td>
</tr>
<tr>
<td class="combat">9185</td>
<td class="combat">7515</td>
<td class="combat">9185</td>
<td class="total-combat"></td>
</tr>
</tbody>
</table>
jquery
$(document).ready(function () {
//iterate through each row in the table
$('tr').each(function () {
//the value of sum needs to be reset for each row, so it has to be set inside the row loop
var sum = 0
//find the combat elements in the current row and sum it
$(this).find('.combat').each(function () {
var combat = $(this).text();
if (!isNaN(combat) && combat.length !== 0) {
sum += parseFloat(combat);
}
});
//set the value of currents rows sum to the total-combat element in the current row
$('.total-combat', this).html(sum);
});
});

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/

JQuery not grabbing HTML data

I have the following HTML table displayed on my webpage.
<div class="timecard">
<table class="misc_items timecard_list" border="0" cellpadding="2" cellspacing="0" style="margin:0 auto;">
<tbody>
<tr class="display_row odd">
<td align="left" class="job_code" style="color:#000099">2400-Orchard</td>
<td align="right">9:47am</td>
<td align="right">5/19/2014</td>
<td align="right" class="hrs">01:00</td>
</tr>
<tr class="display_even odd">
<td align="left" class="job_code" style="color:#000099">1500-Emerald</td>
<td align="right">12:37am</td>
<td align="right">5/17/2014</td>
<td align="right" class="hrs">0:30</td>
</tr>
</tbody>
</table>
</div>
<div id="total"></div>
Then I have the following jquery script that grabs the total times for each job_code and adds them up and displays them. However, it does not seem to be working properly. It isn't displaying the totals added up by the jQuery statement underneath the HTML table as it should be.
$(document).ready(function () {
var timeString = $(this).next('td.hrs').text();
var components = timeString.split(':');
var seconds = components[1] ? parseInt(components[1], 10) : 0;
var hrs = parseInt(components[0], 10) + seconds / 60;
total += hrs;
var temp = [];
$('.job_code').each(function (index, element) {
var text = $(this).text();
temp.push(text);
});
// remove duplicates
var job_code = [];
$.each(temp, function (index, element) {
if ($.inArray(element, job_code) === -1) job_code.push(element);
});
var sum = {};
$.each(job_code, function (index, element) {
var total = 0;
$('.job_code:contains(' + element + ')').each(function (key, value) {
var timeString = $(this).siblings('td.hrs').text();
var components = timeString.split(':');
var seconds = components[1] ? parseInt(components[1], 10) : 0;
var hrs = parseInt(components[0], 10) + seconds / 60;
total += hrs;
sum[index] = {
'job_code': element,
'total': total
};
});
});
console.log(sum);
$.each(sum, function (index, element) {
$('#total').append('<p>Total for ' + element.job_code + ': ' + element.total + '</p>');
});
});
http://jsfiddle.net/2D5fb/1/
Any ideas are greatly appreciated. Thanks.
Aside from total not being defined, change:
var timeString = $(this).next('td.hrs').text();
to
var timeString = $(this).siblings('td.hrs').text();
.next() literally only looks at the next element and td.hrs isn't the next one. .siblings() however will run through all the siblings.
jsFiddle example

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