JQuery + Add checkbox values

I have a page with several checkboxes. Each flag is for a different element (virtual rose), and the rose has a different meaning. I put the rose value in the value = "" checkbox. I need to add the total value of the checked flags - for example: 100, 230, etc. The only other factor is that I only need to add flags with the "giftsRosesCheckBox" class.

<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 the push in the right direction will be great.

Thank you very much.

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

You can iterate 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 .

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

Source: https://habr.com/ru/post/1384660/


All Articles