Reputation: 68680
How do I limit the scope to each group so the sold value reflects the numbers for that group?
jQuery:
var sales = (function calculateSales(){
$( "h1 small" ).each(function() {
var group = $(this).parent('.group');
var numItems = group.find('.btn').length;
var sold = group.find('.btn.hidden').length;
$(this).text(sold+" of "+numItems+" sold");
});
return calculateSales;
}());
HTML:
<div class="group">
<h1>Title <small>Value</small></h1>
<div>
<a href="#" class="btn"></a>
</div>
<div>
<a href="#" class="btn hidden"></a>
</div>
</div>
<div class="group">
<h1>Title <small>Value</small></h1>
<div>
<a href="#" class="btn"></a>
</div>
<div>
<a href="#" class="btn hidden"></a>
</div>
</div>
Upvotes: 0
Views: 47
Reputation: 388316
var group = $(this).parent('.group');
should be var group = $(this).closest('.group');
The .parent() method searches only the parent node of the searching set(small
in this case), so it will look only at h1
which does not satisfies the given selector thus it won't return anything.
Since you want to look at the ancestral tree use .closest()
var sales = (function calculateSales() {
$("h1 small").each(function() {
var group = $(this).closest('.group');
var numItems = group.find('.btn').length;
var sold = group.find('.btn.hidden').length;
$(this).text(sold + " of " + numItems + " sold");
});
return calculateSales;
}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="group">
<h1>Title <small>Value</small></h1>
<div>
<a href="#" class="btn"></a>
</div>
<div>
<a href="#" class="btn hidden"></a>
</div>
</div>
<div class="group">
<h1>Title <small>Value</small></h1>
<div>
<a href="#" class="btn"></a>
</div>
<div>
<a href="#" class="btn hidden"></a>
</div>
</div>
Upvotes: 2