2011-12-05 58 views
4

我有一個包含多個複選框的頁面。 每個複選框用於不同的項目(虛擬玫瑰),玫瑰有不同的值。 我已將玫瑰的值放入複選框的value =「」中。 我需要加上勾選的複選框的總數 - 例如:100,230等。 唯一的其他因素是我只需要添加類「giftsRosesCheckBox」的複選框。Jquery + Add Up複選框值

<table id="tableGiftsWhiteRose"><tr> 
    <td colspan="2">White Rose</td></tr><tr> 
    <td><input type="checkbox" class="giftsRosesCheckBox" value="100"/></td> 
    <td class="credits">100 credits</td> 
</tr></table> 

<table id="tableGiftsRedRose"><tr> 
    <td colspan="2">Red Rose</td></tr><tr> 
    <td><input type="checkbox" class="giftsRosesCheckBox" value="130"/></td> 
    <td class="credits">130 credits</td>  
</tr></table> 

<table><tr> 
    <td colspan="2">Stunning Red Rose</td></tr><tr> 
    <td><input type="checkbox" class="giftsRosesCheckBox" value="150"/></td> 
    <td class="credits">150 credits</td>  
</tr></table> 

我真的不知道如何做到這一點,所以一個正確的方向推動將是偉大的。

非常感謝。

回答

3
$(".giftsRosesCheckBox").click(function() { 
    var total = 0; 
    $(".giftsRosesCheckBox:checked").each(function() { 
     total += parseInt($(this).val(), 10); 
    }); 
    alert(total); 
}); 
4

您可以遍歷複選框並添加它們的值。

var total = 0; 
$(':checkbox:checked.giftsRosesCheckBox').each(function() { 
    total += +this.value; 
}); 

jsFiddle

如果你沒有支持舊的瀏覽器(或墊片reduce()),你可以在一個功能更強大的方式做到這一點...

var total = $(':checkbox:checked.giftsRosesCheckBox') 
      .get() 
      .reduce(function(total, checkbox) { 
       return total + +checkbox.value; 
      }, 0); 

jsFiddle

+0

+1打我吧 – Amerdrix

0
var total =0; 
$('input[type=checkbox].giftsRosesCheckBox, input[checked=checked].giftsRosesCheckBox').each(function(){ 
total += this.val(); 
});