Thanks to the invaluable assistance of several Stack Overflow participants, I'm very close to the desired results ... here's a recap and update, for interested parties:
I have a series of product modules, each of which contains (among other things) the product's name and a 'compare' checkbox. My objective is to generate a list of selected products in another area of the page when the checkboxes are checked. As there must be a function to check for a minimum of two, and some arbitrary maximum - either as part of the checkbox .click function (per Brian's version, thanks again for your invaluable help), or on the submit (which I'm leaning towards). In either case, the number of items in the list is apparently being mis-counted; w/zero or one checkbox checked, I correctly get an alert of insufficient items; however, if I uncheck and recheck a few times, my code is reporting the incorrect number of items in the list.
In the interest of brevity (!), I'll forego posting both versions, since I'm experiencing similar oddity in both. Here's my latest cobbling - many thanks in advance for any insight.
<div class="product-module">
<div class="product-pic">
<div class="checkbox-wrapper">
<label for="compare1">
<input type="checkbox" class="checkbox" name="compare" id="compare1" />
Compare
</label>
</div>
</div>
<div class="product-info">
<p>
<a href="#" title="#"><span class="product-name">Product Name here</span></a><br />
</p>
</div>
<div class="compare">
<ul>
</ul>
<p class="error" style="display: none;">ACK! You've selected more than 4 products to compare.</p>
<p class="compare-button"><button type="submit">Compare</button></p>
<p class="clear-selections"><a class="button" id="clear-selections" href="#">Clear Selections</a></p>
<script type="text/javascript">
$(function(){
$('input[type="checkbox"]').attr('checked', false);
});
$(function(){
$('input[type="checkbox"]').click(function(){
var title = $(this).closest('.product-module').find('.product-name').html();
// as user checks the checkbox, add the item to the ul
if($(this).attr('checked')){
var html = '<li><a href="'+title+'">' + title + '</a></li>';
$('.compare ul').append(html);
} else {
// if user is un-checking the checkbox, remove the item from the ul
// orig: $('li[title="' + title + '"]').remove();
$('li a[href="' + title + '"]').remove();
}
});
});
$(function(){
$('.clear-selections').click(function(){
$('.compare ul').empty();
$('input[type="checkbox"]').attr('checked', false);
})
});
$(function(){
$('.compare button').click(function(){
minRequests = 2;
maxRequests = 4;
requested = $('.compare ul li').size(); // go figure: why not .length()?
if(requested < 2) {
alert ('Compare ' + requested + ' products?');
} else if((requested >= 2) && (requested <= 5 )) {
alert ('There are ' + requested + ' products to compare');
} else {
alert (requested + ' is too many');
}
});
});