I have a CheckBox list and I want to get the number of items selected when a checkbox is checked/unchecked.
checkCount is always 0开发者_运维问答. It seems to me like checkCount is getting assigned when the page loads and the getCheckCount function is never called again. Why doesn't this work and how can I get the event to have an up to date checkCount? Thank you.
$(function () {
$('#<%=cblInterests.ClientID%> input').click(function () {
var checkCount = getCheckCount();
alert(checkCount);
return checkCount < 2;
});
});
function getCheckCount() {
return $('#<%=cblInterests.ClientID%>').children('input:checked').length;
}
Use the .change()
event, not the .click()
event.
$(function () {
$('#<%=cblInterests.ClientID%>').delegate('input', 'change', function () {
var checkCount = getCheckCount();
alert(checkCount);
return checkCount < 2;
});
});
function getCheckCount() {
return $('#<%=cblInterests.ClientID%> input:checked').length;
}
the use of .delegate (or .live) allows you to add inputs on the fly.
精彩评论