1
<td  class="sum"><?php echo $item->get('unit_price') * $item->get('quantity'); ?></td>
<td  class="sum"><?php echo $item->get('unit_price') * $item->get('quantity'); ?></td>
<td  class="sum"><?php echo $item->get('unit_price') * $item->get('quantity'); ?></td>
<td  class="sum"><?php echo $item->get('unit_price') * $item->get('quantity'); ?></td>
<tr><td id="total"></td></tr>

I tag the TD with 'sum' and I use javascript like below:

<script>
var sum = 0;
$('.sum').each(function() {
        sum += sum;
});
$('#total').text(sum);
</script>

I know it does not work, I am new to Javascript.Thanks a lot!

3
  • try var sum = $('.sum').length Commented Sep 3, 2014 at 10:40
  • Replace your sum = +sum; by sum++; Commented Sep 3, 2014 at 10:43
  • @impaler what exactly do you want the result? the sum of value inside tag td or the number of td's? Commented Sep 3, 2014 at 10:45

2 Answers 2

1

Should just be something like:

  // Gets the number of elements with class yourClass
  var totalTd = $('.sum').length;
  $('.total').text(totalTd);
Sign up to request clarification or add additional context in comments.

Comments

0

Inside of each loop you must take current value of the td (its innerText converted to Number) and add to sum:

var sum = 0;
$('.sum').each(function() {
    sum += Number($(this).text());
});

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

Also you should add colspan="4" to td#total to make HTML valid.

Demo: http://jsfiddle.net/7f0todr1/

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.