2011-09-17 35 views
0

我有一個複選框列表,我希望獲取複選框被選中/取消選中時選中的項數。使用jquery幫助函數內部的函數

checkCount始終爲0.在我看來,似乎checkCount在頁面加載時得到分配並且getCheckCount函數再也不會被調用。爲什麼這不起作用,我怎樣才能讓事件獲得最新的checkCount?謝謝。

$(function() { 
     $('#<%=cblInterests.ClientID%> input').click(function() { 
      var checkCount = getCheckCount(); 
      alert(checkCount); 
      return checkCount < 2; 
     }); 
    });   

    function getCheckCount() { 
     return $('#<%=cblInterests.ClientID%>').children('input:checked').length; 
    } 
+0

複選框直接位於#client-id之下嗎?如果沒有,使用「查找」而不是「子女」 – ABentSpoon

回答

1

使用.change()事件,而不是.click()事件。

+0

同樣的問題,計數仍然是0. – Mike

+0

這將有助於,如果你可以顯示你的標記。但是,請嘗試將'.children(...)'更改爲'.find(...)'。 –

+0

這樣做。萬分感謝! – Mike

0
$(function() { 
     $('#<%=cblInterests.ClientID%>').delegate('input', 'change', function() { 
      var checkCount = getCheckCount(); 
      alert(checkCount); 
      return checkCount < 2; 
     }); 
    });   

    function getCheckCount() { 
     return $('#<%=cblInterests.ClientID%> input:checked').length; 
    } 

使用.delegate(或.live)允許您即時添加輸入。