0

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>

1
  • 1
    White text on a white background isn't a good idea :) Commented Apr 3, 2016 at 2:05

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.