I am creating a task list with Parent and Child tasks. They are laid out in an ordered list and are nested many levels deep, so a parent task can have child tasks and parent tasks inside as well.
Example:
<div class="item-list">
<ol>
<li class="parent">
<div class="title">Im a task</div>
<div class="totalhours">total child hours here please</div>
<ol>
<li>
<div class="title">Im a task</div>
<div class="hours">5</div>
</li>
<li>
<div class="title">Im a task</div>
<div class="hours">10</div>
</li>
<li class="parent">
<div class="title">Im a task</div>
<div class="totalhours">total child hours here please</div>
<ol>
<li>
<div class="title">Im a task</div>
<div class="hours">5</div>
</li>
<li>
<div class="title">Im a task</div>
<div class="hours">10</div>
</li>
</ol>
</li>
</ol>
</li>
<li>Another task thats not a parent on this level</li>
</ol>
</div>
So each level I would like to have a total of all nested items. So the very top Parent Task includes the hours of ALL NESTED hours div and then if you drill down it each nested parent does the same for all its nested hours and so on.
This is what I am using at the moment and its just calculating every single hour div instead of only nested and placing the same number everywhere.
var totalest = $('li.parent .totalhours');
var sum = 0;
$("li .hours").each(function() {
var val = $.trim( $(this).text() );
if ( val ) {
val = parseFloat( val.replace( /^\$/, "" ) );
sum += !isNaN( val ) ? val : 0;
}
totalest.html(sum);
});
I’m hoping for this result
- I’m a Parent task 30 hours
- Im a task 5 hours
- Im a task 10 hours
- Im a Parent task 15 hours
- Im a task 5 hours
- Im a task 10 hours
- I’m another Parent task 20 hours
- Im a task 5 hours
- Im a task 5 hours
- Im a Parent task 10 hours
- Im a task 5 hours
- Im a task 5 hours
Loop through each parent and add hours only to that parent.
http://jsfiddle.net/qqhD6/