I am trying to count the checkhed checkboxes. See her: http://jsfiddle.net/2bCdR/2/ The Jquery counter does not work and does also deactive the other Jquery.
My Jquery {
$.each($('div.category'), function () {
var categoryDiv = $(this);
function countChecked() {
var n = $("categoryDiv input:checked").length;
$("categoryDiv #counter").text(n);
}
}
countChecked();
$(":checkbox").click(countChecked);
My HTML
<form accept-charset="UTF-8" action="/" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8"开发者_如何学Python type="hidden" value="✓" /></div>
<div class="menuitem category">
<label for="search_company1">company1</label>
<input name="search[company1_is_true]" type="hidden" value="0" />
<input id="search_company1_is_true" name="search[company1_is_true]" type="checkbox" value="1" />
<div id="counter"></div>
</div>
<div class="menuitem category">
<label for="search_company3">company3</label>
<input name="search[company3_is_true]" type="hidden" value="0" />
<input id="search_company3_is_true" name="search[company3_is_true]" type="checkbox" value="1" />
<div id="counter"></div>
</div>
<div class="hidediv">
<div class="menuitem">
<label for="search_company2">company2</label>
<input name="search[company2_is_true]" type="hidden" value="0" />
<input id="search_company2_is_true" name="search[company2_is_true]" type="checkbox" value="1" />
</div>
</div>
<input id="search_submit" name="commit" style="display:none;" type="submit" value="Submit" />
</form>
var checked = $(':checkbox:checked', '.menuitem, .hidediv').length;
Check a working example out here
1 - You have duplicate 'counter' div IDs. You should change them to classes (IDs should never be duplicated).
2 - You do not need a loop. A single click handler with appropriate traversal will do it.
$(":checkbox").click(function() {
// find closest category parent div
var $cat = $(this).closest(".category");
// get checkbox within category, check length
var len = $cat.find(":checkbox:checked").length;
// update the div's counter
$cat.find(".counter").text(len);
});
Demo: http://jsfiddle.net/mvdnj/1/
精彩评论