Reputation: 874
I've got a mail box menu which you can right-click and choose to delete a folder which looks a bit like the following:
<ul>
<li>
Level 1
<span class="badge badge-success MailCount">60</span>
<ul>
<li>
Level 2 a
<span class="badge badge-success MailCount">10</span>
<ul>
<li>
Level 2 a i
<span class="badge badge-success MailCount">10</span>
</li>
<li>
Level 2 b ii
<span class="badge badge-success MailCount">10</span>
</li>
<li>
Level 2 c iii
<span class="badge badge-success MailCount">10</span>
</li>
</ul>
</li>
<li>
Level 2 b
<span class="badge badge-success MailCount">10</span>
</li>
<li>
Level 2 c
<span class="badge badge-success MailCount">10</span>
</li>
</ul>
</li>
</ul>
And my Javascript file looks like the following;
$(document).ready(function() {
"use strict";
$(document).on('click', function(e) {
var action = $(e.target).data('action'),
anchor = '',
clicked = $('.clicked'); // This is applied when you right-click teh item
switch (action) {
// Rename a mail sub-folder...
case 'rename-folder':
break;
}
});
});
So at this point in time, all I simply do is clicked.remove();
however now I'd like to take the .clicked > .MailCount
value and take it away from all .MailCount
above and if .clicked
has direct ul
which are going to also be deleted, their values should be added up with the current and removed from the above value.
I hope I haven't made that sound more complicated than what it is. Basically if you remove Level 2 a
, it'll add up Level 2 a
+ Level 2 a i
+ Level 2 a ii
+ Level 2 a iii
and take them away from Level 1
Upvotes: 0
Views: 58
Reputation: 782148
Use .map()
to loop over all the .MailCount
elements in the li
being removed and add up all their contents. Then subtract it from the total in the top-most .MailCount
.
var remove_total = 0;
clicked.find(".MailCount").map(function() {
remove_total += parseInt($(this).text(), 10);
});
clicked.parents("li").last().find(".MailCount").first().text(function(i, oldText) {
return parseInt(oldText, 10) - remove_total;
});
clicked.remove();
Upvotes: 1
Reputation: 874
case 'delete-folder':
var thisUnread = clicked.find('.MailCount:first').text();
clicked.parents('li').each(function() {
var parentUnread = $(this).find('.MailCount:first').text();
if ((parentUnread - thisUnread) > 0 ) {
$(this).find('.MailCount:first').text((parentUnread - thisUnread));
} else {
$(this).find('.MailCount:first').remove();
}
clicked.remove();
});
break;
Upvotes: 0