Jquery + Add Up Checkbox Values

我们两清 提交于 2021-02-08 23:38:25

问题


I have a page with a number of checkboxes. Each Checkbox is for a different item (virtual Rose) and rose has a different value. I have put the value of the rose into the value="" of the checkbox. I need to add up the total value of the ticked checkboxes - eg: 100, 230 etc. The only other factor is I need to only add up checkboxes with the class "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>

I'm really not sure how to do this so a push in the right direction would be great.

thanks so much.


回答1:


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



回答2:


You could loop over the checkboxes and add their values.

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

jsFiddle.

If you didn't have to support older browsers (or shim reduce()), you could do it in a more functional way...

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

jsFiddle.




回答3:


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


来源:https://stackoverflow.com/questions/8382622/jquery-add-up-checkbox-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!