2011-12-05 57 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(); 
});