sana
sana

Reputation: 460

sum all values for table column on html page

I have a sample table look like this and data refreshed every 5 minute to show latest.example -

TollFree                    US                      Canadian                      
7,312                       826                     141,128     

I need to add and calculate total of above all.

 Total Records -

This is what i have tried so far- http://jsfiddle.net/unKDk/2666/

HTML page has 6 tables which has different number of columns to do same calculation. Trying to use same script in all as td class is same.

Upvotes: 4

Views: 18638

Answers (2)

acnn
acnn

Reputation: 226

There were a few errors in your code. Here is the working version : http://jsfiddle.net/2q06sv8w/3/

$(document).ready(function () {
            var expenses = $('.expenses');
            var expenseTotal = $('#expenses_sum');
            expenseTotal.html('0');
            $.each(expenses, function (index, object) {
                var boldTag = $(object).find('b');
                if (boldTag && boldTag.length > 0 && $(boldTag[0]).html() != '') {
                    expenseTotal.html(parseInt(expenseTotal.html()) + parseInt($(boldTag[0]).html().replace(/,/g, '')));
                }
            })
        });
  1. The selector '.' is used to select elements matching a class name and '#' is used to select an element matching an id. So 'expenses_sum' must be an id and not a class.
  2. You should use html() and not val() to get and set the content of a td tag.
  3. The td tag contains the value inside a bold tag so you must use the html() on the bold tag.
  4. Declaring global variables and using $ prefix for variables does not look necessary here.

Upvotes: 2

Marco Salerno
Marco Salerno

Reputation: 5203

Here we go:

var summ = Number($("td:nth-child(1)").text()) + Number($("td:nth-child(2)").text()) + Number($("td:nth-child(3)").text());
console.log("Result: " + summ);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>A</th>
<th>B</th>
<th>V</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>

Edit for your request:

var summ = 0;
$("td").each(function() {
  summ += Number($(this).text());
});;
console.log("Result: " + summ);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>A</th>
<th>B</th>
<th>V</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>

Upvotes: 5

Related Questions