function calcTotal() {
var total = 0;
$('input[name="fruit"]:checked').each(function() {
total += parseFloat(this.value);
});
$('#totalPrice').text(total.toFixed(2));
}
// 事件委託(動態添加商品也生效)
$(document).on('change', 'input[name="fruit"]', calcTotal);
進階擴展:數量調整、單價顯示、刪除、全選
<!-- 單行商品模板 -->
<div class="cart-row" data-id="1">
<input type="checkbox" class="item-chk" value="10">
<span class="name">蘋果</span>
<span class="price">¥10.00</span>
<button class="qty-minus">-</button>
<input type="text" class="qty" value="1" min="1">
<button class="qty-plus">+</button>
<span class="subtotal">¥10.00</span>
<button class="del">刪除</button>
</div>
<script>
$(".cart-list").on("change keyup click", ".item-chk, .qty, .qty-minus, .qty-plus, .del", function() {
var $row = $(this).closest(".cart-row");
var price = parseFloat($row.find(".item-chk").val());
var qty = parseInt($row.find(".qty").val()) || 1;
if ($(this).is(".qty-minus")) qty = Math.max(1, qty - 1);
if ($(this).is(".qty-plus")) qty += 1;
if ($(this).is(".qty")) qty = Math.max(1, parseInt(this.value) || 1);
$row.find(".qty").val(qty);
$row.find(".subtotal").text("¥" + (price * qty).toFixed(2));
if ($(this).is(".del")) $row.remove();
calcGrandTotal();
});
function calcGrandTotal() {
var total = 0;
$(".cart-row").each(function() {
if ($(this).find(".item-chk").is(":checked")) {
total += parseFloat($(this).find(".subtotal").text().replace("¥", ""));
}
});
$("#grandTotal").text("¥" + total.toFixed(2));
}
</script>