I assume jQuery is flagged from your question, that you are using jQuery.
If you had such divs (note the few classes that I added):
<div class="oddrow rows_to_add"> <span class="title">1 - 1215 - Magna Carta</span><br/> <span class="size">size: <span class="size">229.1</span> MB</span> <input name="1215 - Magna Carta" class="add_when_checked" type="checkbox"> <div> <div class="evenrow rows_to_add"> <span class="title">1 - 1215 - Magna Carta</span><br/> <span class="size">size: <span class="size">229.1</span> MB</span> <input name="1215 - Magna Carta" class="add_when_checked" type="checkbox"> <div>
And the full div:
<div id="total>total = <span id="total"></span></div>
JQuery code to summarize them:
$( '.add_when_checked' ).change( function() { var total = 0; $( '.rows_to_add' ).each( function() { var $this = $( this ); if ( $this.find( '.add_when_checked' ).attr( 'checked' ) ) { total += $this.find( '.size' ).html(); } } ); $( '#total' ).html( total ); } );
This basically means that when a flag changes state, a loop through all the divs with the "rows_to_add" class is checked when the flag contained in the "add_when_checked" class is checked, and if so, add a value within the range using the "size" class to the bottom line. Once you have the total, put it in a div with the identifier "total".
Another way could be something like this:
$( '.add_when_checked' ).change( function() { var total = 0; $( '.add_when_checked:checked' ).each( function() { total += $( this ).parent().find( '.size' ).html(); } ); $( '#total' ).html( total ); } );
Uses a selector to determine which checkboxes are checked instead of conditional, then uses the parent traversal to find the appropriate size.
source share