Get Sum of 2nd <td> in every <tr> in Table - javascript

I want to calculate the sum of the 2nd <td> item in each of the rows and sum the total into my div.
My JS is as follows
$('.table tbody tr:gt(0)').each(function () {
var mixTotal = parseInt($(this).find('td:nth(2)').html());
// Add total to div
$('.totals').text(mixTotal);
});
DEMO HERE http://jsfiddle.net/5pnMh/1/
My Html is a standard HTML table, which contains a thead tbody and tfoot.
I can't seem to get it to work. I can get each value but not sure how to add them.
Looking for some help

var mixTotal = 0;
$('tbody tr').each(function () {
mixTotal += parseInt($(this).find('td:eq(1)').text(),10);
});
$('.totals').html(mixTotal);
jsFiddle
Your last row of numbers will not be included in the TOTAL because it is a <tfoot>. Please also note that just because your first row is a <thead>, you may not leave out the <tr></tr> tags.

I think is better store the result in variable and after loop append it to div.
// Set global var
var mixTotal = 0;
$('.table tbody tr').each(function () {
// Just add the number
mixTotal = mixTotal+parseInt($(this).find('td:nth-child(2)').html());
});
// And finally, add total to div
$('.totals').text(mixTotal);
http://jsfiddle.net/5pnMh/3/
If you will replace :nth(2) to a :nth-child(2), your code may partly works.

If you're looking to sum the values in the second column, try this:
var mixTotal = 0;
$('.table tbody tr').add('.table tfoot tr').each(function () {
mixTotal += parseInt($(this).find('td:eq(1)').text(), 10);
});
$('.totals').text(mixTotal); // Add total to div
jsFiddle example

use this code if you got decimal numbers
var mixTotal = 0;
$('tbody tr').each(function () {
mixTotal += parseFloat($(this).find('td:eq(1)').text(),10);
});
$('.totals').html(mixTotal);
See Demo

var mixTotal = 0;
$('#your_table_id tbody tr').each(function () {
mixTotal = mixTotal + (isNaN(parseInt($(this).find('td:eq(1)').text(), 10)) ? 0 : parseInt($(this).find('td:eq(1)').text(),10))
});
$('.totals').html(mixTotal);
if u have both types of values like text or nan value

Related

How to make table that returns average grade of students with button?

I have been trying to make a table with names and grades of people, while using a button that when clicked it will calculate the average of all the grades that were put inside the table until then.
first I tried just to sum it but with no sucess.
$("button").click(function ()
My codepen is here
I got it working with this javascript
$("button").click(function () {
var sum = 0;
var quantity = 0;
$("tbody tr").each(function(index) {
sum += parseInt($(this).find("td:nth-child(2)").text() , 10);
quantity++;
});
$("tfoot tr:last-child td:last-child").text(sum/quantity);
});

creating a 2 column table dynamically using jquery

I am trying to generate a table dynamically using ajax call. To simplify things i have just added my code to js fiddle here -> http://jsfiddle.net/5yLrE/81/
As you click on the button "HI" first two columns are created properly.. but some how as the td length reaches 2 . its not creating another row. The reason is that when i do find on the table elements its actually retrieving the children table elements. Can some one pls help.
I want a two column table.. Thank you.
sample code:
var tr = $("#maintable tbody tr:first");
if(!tr.length || tr.find("td:first").length >= max) {
$("#maintable").append("<tr>");
}
if(count==0) {
$("#maintable tr:last").append("<td>hi"+content+"</td>");
}
Basically the matching of descendants was allowing for great great grandchildren etc. Just needed to make the matching more specific.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/5yLrE/91/
max = 2
$("button").click(function () {
var content = $('#template').html();
var $table = $("#maintable");
var tr = $table.find(">tbody>tr:last");
if (!tr.length || tr.find(">td").length >= max) {
// Append a blank row
tr = $("<tr>");
$table.append(tr);
}
tr.append("<td>hi " + content + "</td>");
});
This one always targets the last row and adds a row if it does not exists at all (or there are too many divs already) which is what I gather you intended.
I also used the templating I suggested to separate messy HTML strings from the code.
You will want to check the length of the table cells before incrementing a new table row. After you have reached your max column length, reset the row and start over.
JSFiddle
max_columns = 2;
count=0;
$("button").click(function() {
var content='column';
if(count==max_columns||!$('#maintable tr').length){
$("#maintable").append("<tr>");
count=0;
}
if(count!=max_columns)
$("#maintable tr:last").append("<td>"+content+"</td>");
else
$("#maintable tr:first").append("<td>"+content+"</td>");
count++;
});

How to change row number when add\delete rows

I have integrated add row and delete row functionality in my table. If i add row second row number is also 1. I need to change number of each row as per every add and delete like 1, 2 etc.
I used the code from this fiddle http://jsfiddle.net/MJGV2/6/.
How to achieve this? Any help would be appreciated. Thanks.
You can add this:
var renum = 1;
$("tr td strong").each(function() {
$(this).text(renum);
renum++;
});
See this Fiddle demo.
There are a lot of errors in your code - for example all id needs to be unique and you should fix this.
For example, you can add call recalculate function, like this:
function recalculate() {
var i = 1;
$(".numberRow").each(function() {
$(this).find("strong").text(i++);
});
}
Where numberRow is css class on td, where store number of row.
I add this in your jsfiddle example
There were lot of things missing in your code. i have tuned everything properly
JS CODE:
$("input[type='button'].AddRow").on('click',
function () {
if ($(this).val() == 'Delete') {
trSet = $(this).closest('tr').nextAll();
currIndex = $(this).closest('tr').find('td span').html();
$(this).closest('tr').remove();
trSet.each(function () {
$(this).find('td span').html(currIndex);
currIndex++;
});
count = currIndex - 1;
} else {
var $tr = $(this).closest('tr').clone(true);
var $input = $tr.find('input.startdatum');
++count;
$tr.find('td span').html(count);
$(this).val('Delete');
var id = 'datepicker' + count;
$input.attr('id', id).data('index', count);
console.log(count);
$tr.appendTo($(this).closest('table'));
setdatepicker();
}
});
LIVE DEMO:
http://jsfiddle.net/MJGV2/14/
Happy Coding :)

Using jQuery to remove all rows in a table after a specified row

I'd like to delete all rows in a table after row x where x is a number that switches up. The following does not work:
$("#comps-table tbody tr:gt(x)").remove();
Nor does:
$('#comps-table tbody tr').gt(x).remove();
x is a variable so you need to use string concatenation.
$("#comps-table tbody tr:gt(" + x + ")").remove();
or the preferred way is to use slice()
$('#comps-table tbody tr').slice(x).remove();
Try this:
var after = 5; // remove after row number 5
$('#comps-table tbody tr').each(function() {
var $row = $(this);
var rowNumber = $row.index();
if ( rowNumber >= after ) {
$row.remove();
}
});
Havent tested it but it should put you in the right direction

Getting third cell of each row

var Rows = $("#tableid tbody tr");
Rows.each(function(index, element) {
var thirdCell = $(this+":nth-child(3)").text();
alert(thirdCell);
});
Something in the var thirdCell line is not working correctly. Each row has four children, all td tags. I want to get the text inside the third cell.
Try something like below,
var Rows = $("#tableid tbody tr");
Rows.each(function(index, element) {
var thirdCell = $(this).find('td').eq(2).text();
alert(thirdCell);
});
this is not a string, it's a jquery object, so it can't be appended to when you are building your new selector. You could do it like this:
var selector = $(this).selector;
var thirdCell = $(selector+":nth-child(3)").text();
alert(thirdCell);
http://jsfiddle.net/2URV7/
This will not work because tr has no text. it has TDs. you can apply though html() to get the innerHTML of the tr, or use text() on tds if they actually contain text.
you can get all cells from each row by 0 based index
Rows.each(function(index, element) {
var thirdCell = $(this.cells[2]).text();
alert(thirdCell);
});
or you can get it in original selector
var Third = $("#tableid tbody tr > td:nth-child(3)");
Third.each(function(index, element) {
var thirdCell = $(this).text();
alert(thirdCell);
});

Categories