开发者

Help with function inside of event using jquery

开发者 https://www.devze.com 2023-04-05 09:16 出处:网络
I have a CheckBox list and I want to get the number of items selected when a checkbox is checked/unchecked.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消