user4635038
user4635038

Reputation:

Calculate total of values in table cells using jquery

I have a table with values as shown below,

<table>
    <tbody>
        <tr>
            <td class='price'>5</td>
        </tr>
        <tr>
            <td class='price'>NA</td>
        </tr>
        <tr>
            <td class='price'>10</td>
        </tr>
        <tr>
            <td class='price'>NA</td>
        </tr>
        <tr>
            <td class='price'>20</td>
        </tr>
        <tr>
            <td class='total'></td>
        </tr>
    </tbody>
</table>

My task is to calculate the total of valid values (5, 10 and 20) and display the sum in total cell. The code I tried is,

var prices = $('.price'),
    total = 0;

$.each(prices, function(i, price) {
    if (price != 'NA') {
         total = total + price;
    }
});

$('.total').text(total);

The issue I am facing is, I am not getting the correct output. Sometimes, the table cell contains empty value instead of 'NA'. I am not sure what I am missing. Please suggest.

Upvotes: 0

Views: 2306

Answers (7)

Oday Fraiwan
Oday Fraiwan

Reputation: 1157

Get all tds using jqyery, loop through all tds using jquery each function, then check if the current td contains a number using isNaN. If so, sum that value to the total.

var sum = 0, elText;
$('.price').each(function (index, element) { 
    elText = element.innerText;
    isNaN(elText) || (sum += parseInt(elText));
});
$('.total').text(sum);

JSFiddle

Upvotes: 0

Niko
Niko

Reputation: 6269

Use isNaN to check if the cell contains a value then convert it:

$.each(prices, function(i, price){
if (!isNaN($(this).text())){
     total = total + Number($(this).text());
}});

Note: if you use "parseInt" it will always return an integer - so if you have decimal values in the table use Number(String) which will try to convert everything that looks like a number...

Upvotes: 1

R4nc1d
R4nc1d

Reputation: 3113

Created a fiddle for you... Fiddle

var total = 0;
$(".price").each(function (i, price) {
    var price = $(this).text();

    if (price != 'NA') {
        total = total + parseInt(price);
    }

    $('.total').text(total);

});

Upvotes: 0

Brijesh Bhatt
Brijesh Bhatt

Reputation: 3830

$(document).ready(function(){
var prices = $('.price');
var total = 0;
$.each(prices, function(i, price)
{
    var val=$(this).text();
    if (val!="NA" && val!="")
       {
         total = total + parseInt(val);
       }
});

$('.total').text(total);
});

Here is the Fiddle

Upvotes: 0

Satpal
Satpal

Reputation: 133403

Since prices is jQuery object use $.fn.each(), then you need to use $.fn.text() to get the text.

Also use parseInt(), to convert string to integer.

Use

var prices = $('.price');
var total = 0;
prices.each(function() {
    var price = $(this).text(); //use the method to get text of cell
    if (price != 'NA') {
        total = total + parseInt(price, 10); //use parseInt to convert to number
    }
});
$('.total').text(total);

$(document).ready(function() {
  var prices = $('.price');
  var total = 0;
  prices.each(function() {
    var price = $(this).text();
    if (price != 'NA') {
      total += parseInt(price, 10);
    }
  });
  $('.total').text(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr><td class='price'>5</td></tr>
<tr><td class='price'>NA</td></tr>
<tr><td class='price'>10</td></tr>
<tr><td class='price'>NA</td></tr>
<tr><td class='price'>20</td></tr>
<tr><td class='total'></td></tr>
</tbody>
</table>

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82241

You need to use the text/html of td element and also parse the value to integer before making the addition:

var prices = $('.price');
var total = 0;
 $.each(prices, function(i, price){
  var pc=$(this).text();  
  if (pc!= 'NA'){
       total = total + parseInt(pc,10);
  }});
$('.total').text(total);

Upvotes: 0

Sudharsan S
Sudharsan S

Reputation: 15393

Your code working fine the issue is you concat the total so Use parseInt() function parses a string and returns an integer.

parseInt($(this).text() , 10);

Syntax

parseInt(string, radix);

Parameters

string

The value to parse. If string is not a string, then it is converted to one. Leading whitespace in the string is ignored.

radix

An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string. Specify 10 for the decimal numeral system commonly used by humans. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.

Upvotes: 0

Related Questions