CRAIG
CRAIG

Reputation: 1029

Using jquery to get the sum of numbers if checkbox is checked

I have a table. Each row has a checkbox and a number in it. The number is within a span with a class.

If the checkbox is checked, I want the number to be added up with all of the other numbers in checked rows. Here is what the row looks like.

 <td><input class="box" type="checkbox" name="selclips[]" value="1234"></td><td><span class="amount">45.00</span></td>
 <td><input class="box" type="checkbox" name="selclips[]" value="1235"></td><td><span class="amount">65.00</span></td>

Then at the bottom I have:

 <td>Total</td><td><div id="total"></div></td>

So, need some help with the JS or jquery to add up those dollar amounts with the span tags and provide a total if the checkbox is checked in that row? So, in the example above, if both boxes were checked, the script would add up 45.00 and 65.00 and put the total of 110 into the Total div. Also, if I un-check the boxes, the amount should change as well.

Thanks very much for any help anyone can give. I really appreciate it!

Upvotes: 0

Views: 3317

Answers (5)

Ginden
Ginden

Reputation: 5317

var total =  Array.prototype.slice.call($('input.box:checkbox:checked'), 0) // changes jQuery object to array of DOM elements
    .reduce(function(a, b) { // calls reduce method
        return a + Number(b.value);
    }, 0);

Simple and fast.

reduce method documentation.

Upvotes: 0

Ringo
Ringo

Reputation: 3965

Try this:

 var total = 0;
$('.box').click(function(){
    if($(this).prop('checked')){
      total += Number($(this).closest('tr').children('td:last-child').text());
  }
    else{
      total -= Number($(this).closest('tr').children('td:last-child').text());
    }
  $('#total').text(total);
});

Here is JSFIDDLE

Upvotes: 1

Adil
Adil

Reputation: 148110

You need something like

Live Demo

$('.box').change(function(){
   var total = 0;
   $('.box:checked').each(function(){
        total+=parseFloat($(this).parent().next('td').find('.amount').text());
   });
   $('#total').text(total);
});

Upvotes: 2

plalx
plalx

Reputation: 43718

This perhaps?

var total = 0,
    $totalEl = $('.total');

$('.box:checkbox').click(function () {
    total += (this.checked? 1 : -1) * +this.parent('td').next().children('.amount').text();
    $totalEl.text(total);
});

Upvotes: 0

Rahul
Rahul

Reputation: 5774

Fairly simple..

$(function(){

    $( ".box" ).on( "click", function(){
        console.log($(this).next().html());
        var total = 0;
        $('.box:checked').each(function(){
         total += parseFloat($(this).next().html());
        });
        $("#total").text('Total is : ' + total);
    });

});

This works..

http://jsfiddle.net/hqR2r/2/

Upvotes: 1

Related Questions