Your markup was not conducive to a clear answer so I pared it down and added a second checkbox to use as an example. Since you used it, I add jQuery to the snippet.
- I added a parent
"myproduct"
class
- When checkbox value CHANGES, I handle that event for every CHECKED checkbox.
- I added a "price" class element with
data
attribute to hold the price value data-product-price="34.29"
- allows me to format the text of the element with $
for instance. This could well be on the checkbox - even as the actual "value" but kept it for your example code.
- I made an assumption prices could be a currency value with two decimal places since you provided none so I parsed that way instead of an integer value.
- Loop through the checked boxes and put the total of them all.
let boxes = $('input[type=checkbox].mything')
let totalPrice = $('#totalPrice');
boxes.on('change', function() {
let boxesPrice = 0;
boxes.filter(':checked').each(function() {
let productPrice = $(this)
.closest('.myproduct')
.find('.price')
.data("product-price");
boxesPrice += parseFloat(productPrice);
});
totalPrice.text(boxesPrice.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="totalPrice"></span>
<form action="/order">
<div class="myproduct">
Product #<span>fun guys</span>
<p>
Price : <span class="price" data-product-price="34.29">$34.29</span>
</p>
<div>
<input class="mything" type="checkbox" value="" />
</div>
</div>
<div class="myproduct">
Product #<span>carrots</span>
<p>
Price : <span class="price" data-product-price="7.84">$7.84</span>
</p>
<div>
<input class="mything" type="checkbox" value="" />
</div>
</div>
<input name="submit" type="submit" value="Make order" />
</form>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…