我有一个包含许多复选框的页面。 每个复选框用于不同的项目(虚拟玫瑰),玫瑰具有不同的值。 我已经将玫瑰的值放入复选框的值=“”。 我需要将勾选复选框的总值相加 - 例如:100,230等。 唯一的另一个因素是我只需要添加“giftsRosesCheckBox”类的复选框。
<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>
我真的不确定如何做到这一点,所以推动正确的方向会很棒。
非常感谢。
答案 0 :(得分:4)
您可以遍历复选框并添加其值。
var total = 0;
$(':checkbox:checked.giftsRosesCheckBox').each(function() {
total += +this.value;
});
如果您不必支持旧版浏览器(或垫片reduce()
),您可以采用更实用的方式进行...
var total = $(':checkbox:checked.giftsRosesCheckBox')
.get()
.reduce(function(total, checkbox) {
return total + +checkbox.value;
}, 0);
答案 1 :(得分:3)
$(".giftsRosesCheckBox").click(function() {
var total = 0;
$(".giftsRosesCheckBox:checked").each(function() {
total += parseInt($(this).val(), 10);
});
alert(total);
});
答案 2 :(得分:0)
var total =0;
$('input[type=checkbox].giftsRosesCheckBox, input[checked=checked].giftsRosesCheckBox').each(function(){
total += this.val();
});