Unable to retieve the particular value of cell on table using javascript - 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/

Related

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

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

javascript: add and remove table row, cant get correct numbering

i have table like this:
<button type="button" onclick="addRow();">Add Row</button>
<table id="item_table" cellspacing="1" cellpadding="1" border=1>
<tr>
<td>No.</td>
<td>text</td>
<td>Action</td>
</tr>
<tr id="theFirstRow">
<td class="itemNumber">1</td>
<td>text</td>
<td><button type="button" onclick="deleteRow(this)">Delete</button> </td>
</tr>
</table>
and JS code like this:
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('item_table').deleteRow(i);
}
var maxID = 0;
function getTemplateRow() {
var x = document.getElementById("theFirstRow").cloneNode(true);
var tbs = null;
var lastRow = 0;
var currentRow = 0;
var numbering = 0;
tbs = document.getElementsByClassName("itemNumber");
lastRow = tbs.length - 1;
currentRow = tbs.length;
console.log("lastRow : " + lastRow);
numbering = parseInt(currentRow, 10) + 1;
console.log("numbering : " + numbering);
x.innerHTML = x.innerHTML.replace('<td class="itemNumber">' + currentRow + '</td>', '<td class="itemNumber">' + numbering + '</td>');
return x;
}
function addRow() {
var t = document.getElementById("item_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
r.parentNode.insertBefore(getTemplateRow(), r);
}
Updated: JSFIDDLE HERE
I cant get the increment numbering and delete row numbering correctly, when i check from console log, the number seem correct. Any help would be great.
I think I would go about this a little bit differently. Here is how I would do it. Maybe it isn't what you were looking for. JSFiddle.
HTML (Take out onclicks, add some ids and classes)
<button id="add" type="button">Add Row</button>
<table id="item_table" cellspacing="1" cellpadding="1" border=1>
<tr>
<td>No.</td>
<td>text</td>
<td>Action</td>
</tr>
<tr id="template">
<td class="itemNumber">1</td>
<td>text</td>
<td><button class="delete" type="button">Delete</button> </td>
</tr>
</table>
JS
(function() {
var template = document.getElementById("template"),
table = document.getElementById("item_table"),
display = template.style.display;
document.getElementById("add").addEventListener("click", function() {
var row = template.cloneNode(true);
row.style.display = display;
row.querySelector(".delete").addEventListener("click", function() {
table.removeChild(this);
}.bind(row));
row.querySelector(".itemNumber").innerHTML = table.children.length - 1;
table.appendChild(row);
});
template.style.display = "none";
}());

How to remove the duplicates for append in my html?

I have create javascript to calulate the total of ext. form json but I have problem is it append twice to #total div I don't know what cause maybe because of renderTable function.can someone help me ??
HTML
<div data-role="collapsible" data-collapsed="true" id="poInfos">
<h3 id="poInfo"></h3>
<table data-role="table" id="productOrders" data-mode="reflow">
<thead>
<tr>
<th>Code</th>
<th>Name</th>
<th>Price</th>
<th>Qty.</th>
<th>Ext.</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<div id="total">
</div>
</div>
</div>
</div>
javascript
//render table view all PO for vendor
function renderTable(data){
var $table = $('#productOrders tbody');
var plist = data[0].pslList;
for(var i in plist) {
var row = $('<tr><td>' + plist[i].prodcd + '</td><td>' + plist[i].prodname + '</td><td class="dollars">' + numberToCurrency(plist[i].price) + '</td><td>' + plist[i].qty + '</td><td>' + numberToCurrency(plist[i].ext) + '</td></tr>');
$table.append(row);
calculateTotal(data);
}
}
//calculateTotal
function calculateTotal(data)
{
var $totalDiv = $('#total');
var tax = 0.00;
var sub = 0.00;
var totalsub_tax = 0.00;
var plist = data[0].pslList;
for(var i in plist) {
sub += plist[i].ext;
totalsub_tax = sub +tax;
}
$totalDiv.append("<strong>Sub:</strong>"+numberToCurrency(sub)+"<br/><strong>Total:</strong>"+numberToCurrency(totalsub_tax) +"<br/>");
}
//convert numberToCurrency
function numberToCurrency(amount) {
var thousandsSeparator = ","
var currencyNum = "";
var amountString = amount.toString();
var digits = amountString.split("");
var countDigits = digits.length;
var revDigits = digits.reverse();
for(var i=0; i<countDigits; i++) {
if ((i%3 == 0) && (i !=0)) {
currencyNum += thousandsSeparator+revDigits[i];
} else {
currencyNum += digits[i];
}
};
var revCurrency = currencyNum.split("").reverse().join("");
var finalCurrency = "$"+revCurrency;
return finalCurrency;
}
});
You're running the function calculateTotal() for EACH item instead of after the items have been dealt with.
for(var i in plist) {
var row = $('<tr><td>' + plist[i].prodcd + '</td><td>' + plist[i].prodname + '</td><td class="dollars">' + numberToCurrency(plist[i].price) + '</td><td>' + plist[i].qty + '</td><td>' + numberToCurrency(plist[i].ext) + '</td></tr>');
$table.append(row);
// not here calculateTotal(data);
}
calculateTotal(data); // here
Your call to calculateTotal(data) is within the loop over plist. You should move it outside.

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