sscirrus
sscirrus

Reputation: 56719

Totalling checked checkboxes amidst changes

I have a page with many checkboxes, each of which are tied to a product with a price. I'm trying to use jQuery to give a real-time readout of the 1) number of products, and 2) total price of the user's selections.

This should be very easy: I would have done something like:

$(input).change( function(){
    var sum = $(input:checked).length
    var price_total = $(input:checked).length * 1.99
})

The Complication

The element or elements being changed are NOT counted in the above code. It seems that when clicking a blank checkbox to check it, jQuery will consider the current element 'not checked' rather than 'checked', i.e. it reflects the checkbox before the change. As a result, my code gets significantly more complicated to accept the changed items.

Is there an elegant and simple way to get around this?

Upvotes: 0

Views: 89

Answers (3)

ColBeseder
ColBeseder

Reputation: 3669

You can select checked boxes like this:

$(input).change( function(){
    var sum = $('input[type=checkbox]:checked').length
    var price_total = sum * 1.99
})

I also used your value of sum for the second calculation. Why not - it makes it faster and more readable. And it works.

Upvotes: 0

AbstractChaos
AbstractChaos

Reputation: 4211

Without out your html i can only guess it. My solution would be to use a data entity like data-price.

HTML

​<input type="checkbox" data-price="1.99" />
<input type="checkbox" data-price="1.95" />
<input type="checkbox" data-price="3.60" />
<input type="checkbox" data-price="2.10" />

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

JQuery

​$('input').change(function() {
    recalcTotal();
});

function recalcTotal() {
var total = 0;
$('input:checked').each(function() {
    total += $(this).data('price'); 
});

 $('#total').html(total);
}
​

fiddle

Note: I made the assumption the price may vary between different products unsure if this would be correct

Upvotes: 1

jackwanders
jackwanders

Reputation: 16020

Not sure if the code you posted is what you're actually running, but among other things, your code is missing quotes in your $ selectors. However, this is working for me:

$(':checkbox').change( function(){
    var sum = $(':checked').length;
    var price_total = sum*1.99;
})​​

jsFiddle DEMO

Upvotes: 1

Related Questions