Behseini
Behseini

Reputation: 6320

How to get sum of a table column using jQuery

I am working on the below code. Why am I not getting the sum of the .app cells?

var total = 0;
$(".app").each(function() {
  total += parseInt($(this).val());
});

$("#total").html(total);
#total {
  height: 100px;
  width: 100px;
  padding: 15px;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%">
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td class="app">50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td class="app">94</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td class="app">94</td>
  </tr>
</table>
<br />
<div id="total"></div>

Upvotes: 0

Views: 37

Answers (2)

Allan Pereira
Allan Pereira

Reputation: 2570

You have to use html():

var total = 0;
$(".app").each(function() {
    total += parseInt($(this).html());
});

$("#total").html(total);

The val() method is used to get value from form elements like inputs and selects. Docs

Upvotes: 1

Sahil
Sahil

Reputation: 3358

Change parseInt($(this).val()); to parseInt($(this).html()); as the td cells do not have any value attribute and change the color property for total to #000(black), as the output will not be visible.

var total = 0;
$(".app").each(function() {
  total += parseInt($(this).html());
});

$("#total").html(total);
#total {
  height: 100px;
  width: 100px;
  padding: 15px;
  color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%">
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td class="app">50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td class="app">94</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td class="app">94</td>
  </tr>
</table>
<br />
<div id="total"></div>

Upvotes: 2

Related Questions