While I’m trying to work out the length of an array :
$('input:checkbox[name="promoOn[]"]').click( function(){
var attributes = [];
$('input:checkbox[name="promoOn[]"]:checked').each(function(index) {
attributes.push($(this).val());
$('#promo-on-total').html(attributes.length);
});
});
For some reason the array.length does not return to 0?
Here are the results:
Checkbox 1, checked = array.length = 1
Checkbox 2, checked = array.length = 2
Checkbox 2, unchecked = array.length = 2
Checkbox 1, unchecked = array.length = 1 (not 0???)
Any ideas what may be wrong?
The problem is that you are running through all checked checkboxes and updating the length value in the
promo-on-totaldiv there, but once you uncheck all checkboxes the loop isn’t executed anymore (so the value isn’t updated).This will give you what you expect I think:
DEMO