2013-10-07 57 views
1

我有一個計數選中的複選框的代碼。選擇時它工作正常,但是當我取消選擇一些已經選擇的複選框時,計數會中斷(計數加1)。jQuery:計數選中的複選框 - 錯誤的計數

HTML:

<div>Number of checkboxes checked: <span id='chck'>0</span></div> 
<table> 
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr> 
    <tr><td><input type='checkbox' /></td></tr>  
</table> 

JS:

$('tr :checkbox').change(function(){ 

    $('#chck').text($(this).add(':checked').length); 

}); 

FIDDLE:http://jsfiddle.net/kAsxj/

+0

添加爲添加的元素。 –

+0

@MthethewRiches是的,我現在可以看到。我認爲這是一個功能,添加選擇器到現有$這 –

+2

它是添加一個選擇器到現有的$ this。但是你最初不檢查$ this是否被檢查。這就是爲什麼當你取消選擇時你會失敗的原因。 – andi

回答

1

試試這個

$('#chck').text($('input[type="checkbox"]:checked').length); 
    //gets all input checkboxes 

或與輸入特定的表,你可以做到這一點

$('#chck').text($(this).closest('table').find(':checked').length); 
//gets all input checkboxes within the table 

DEMO

1

當你check或取消選中一個複選框計數不會自動增加,所以你需要:

$('input[type="checkbox"]').change(function(){ 
    $('#chck').text($('input[type="checkbox"]:checked').length); 
}).change(); 

JS Fiddle demo

1

DEMO

$('tr :checkbox').change(function(){ 
     $('#chck').text($(':checkbox:checked').length); 
    });