This much I have already cobbled together (thanks to Stack Overflowers):
I have a series of product modules, each of which contains a product name and a checkbox. Checking a checkbox adds the corresponding product name to a list elsewhere on the page, un-checking a checkbox removes the coresponding product name from the list. When the user submits the 'Compare' button, I need jQuery to check the number of selections, confirming a minimum of two and an arbitrary maximum.
My problem: the following jQuery is apparently failing to account for items which have been removed (by unchecking). For example, if I check a checkbox, then uncheck it - and it does get unchecked, and it does get removed from the list - and then re-check it, jQuery reports that there are 2 items to be compared.
<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></p>
</div>
</div>
<div class="compare">
<ul>
</ul>
<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>
</div>
Script:
// clear all checkboxes on load
$(function(){
$('input[type="checkbox"]').attr('checked', false);
});
$(function(){
$('.column-main input[type="checkbox"]').click(function() {
var title = $(this).closest('.product-module').find('.product-name').html();
// if 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);
// if user un-checks the checkbox, remove the item from the ul
} else if ($(this).attr('checked', false)) {
$('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 = 3;
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');
}
});
});