Issue On Getting Sum of a Table Column Using jQuery

Can you please take a look at this demo and let me know why I am 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>

Answers 1

  • 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


Related Articles