如何根据选中的复选框计算正确总金额,解决仅读取首个商品值的问题
问题根源
- HTML ID重复:你在PHP循环输出所有商品时,给每个商品的
price输入框、quantity输入框都设置了相同的id值,而DOM规范中id是全局唯一的,document.getElementById()只会返回页面中第一个匹配id的元素,所以你永远只能读取到第一个商品的价格、数量。 - 计算逻辑错误:当前JS逻辑是累计所有选中商品的价格总和后直接乘数量,没有对应每个商品单独计算「单价*对应购买数量」,同时总价赋值放在了循环内部,会产生不必要的重复更新。
修复方案
第一步:修改PHP循环输出部分
把商品单价直接存在复选框的自定义属性中,同时给每个商品的数量输入框设置唯一id,避免重复:
<?php $sql = "SELECT * FROM foods"; $result = mysqli_query($conn, $sql); while($row = mysqli_fetch_assoc($result)) { $name = $row['name']; $descrip = $row['foodDesc']; $pic = $row['pic']; $price = $row['price']; $foodID = $row['foodID']; $quanty = $row['quantity']; echo '<tr> <td valign = "center"> <input name = "foodSelection" type="checkbox" value = "'. $foodID .'" data-price="'.$price.'" onclick="totalSum()"> </td> <td><img src = "../admin/foods/img/'. $pic .'" height = "200px" width = "300px" style = "border-radius: 30px;"></td> <td><h3>'. $name . '</h3></td> <td><p align = "center">₱'. $price .'</p></td> <td><input type="number" name="quantity" id="quantity-'.$foodID.'" min="1" onchange="totalSum()" value = "'.$quanty.'"></td> <td><p class = "accomp-text">'. $descrip .'</p></td> </tr>'; } ?>
第二步:替换JS计算逻辑
function totalSum() { const foodChecks = document.getElementsByName("foodSelection"); const totalInput = document.getElementById("total"); let total = 0; for (let i = 0; i < foodChecks.length; i++) { if (foodChecks[i].checked) { // 取当前选中商品的单价 const price = parseInt(foodChecks[i].dataset.price); // 取当前选中商品对应数量 const foodId = foodChecks[i].value; const quantity = parseInt(document.getElementById(`quantity-${foodId}`).value); // 单个商品小计累加 total += price * quantity; } } // 循环结束后统一更新总价 totalInput.value = total.toFixed(2) + "php"; }
内容的提问来源于stack exchange,提问作者EDMAR BUCSIT JR
相关产品推荐
相关产品推荐

