我有一个表格,该表格的每一行末尾都有一个输入,让用户可以选择要购买的每种商品的数量。我已经编写了一个JavaScript代码,该代码从表的每一行中获取数据并得出总价,但是我找不到提交表单时为何不执行任何操作的原因。它确实显示了控制台日志,但没有显示应该在我的范围内的总数。
代码如下:
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<tr>
<td><?= htmlentities($row['id']); ?></td>
<td><?= htmlentities($row['Article']); ?></td>
<td><?= htmlentities($row['Prix']); ?></td>
<td><?= htmlentities($row['PrixRetour']); ?></td>
<td><?= htmlentities($row['QuantiteeMaximale']); ?></td>
<td><?= htmlentities($row['Projet']); ?></td>
<td><input data-price='<?= floatval($row['Prix']); ?>' data-max-quantity='<?= intval($row['QuantiteeMaximale']); ?>' type="number" name="quantity"></td>
</tr>
<?php
}
?>
</table>
<p>Grand Total: $<span id='grandTotal'></span></p>
<script>
console.log("test1");
const tableEl = document.getElementById('articles')
const grandTotalEl = document.getElementById('grandTotal')
const quantityInputEls = tableEl.querySelectorAll('input[name=quantity]');
(function calTotal() {
console.log("test2");
const updateGrandTotal = (grandTotalEl, inputEls) => {
grandTotalEl.innerText = inputEls.reduce((total, inputEl) => {
const maxQuantity = parseInt(inputEl.dataset.maxQuantity)
if(parseInt(inputEl.value) > maxQuantity) inputEl.value = maxQuantity
if(parseInt(inputEl.value) < 0) inputEl.value = 0
const price = parseFloat(inputEl.dataset.price)
const quantity = parseInt(inputEl.value)
console.log("hello");
if(isNaN(quantity)) return total
return total + (price * quantity)
}, 0)
}
console.log("test3");
quantityInputEls.forEach(el => el.addEventListener('keyup', () => updateGrandTotal(grandTotalEl, inputEls)))
})();
</script>
<?php
} else {
echo "0 results";
}
$conn->close();
?>