I have this function inside of JavaScript that is supposed to calculate the total price of the product selected inside of php. When I load my page, the console logs outside of my function work but the ones inside don't. Do I have a mistake in my code that causes it to not execute?
<?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");
function calTotal() {
console.log("test2");
const tableEl = document.getElementById('articles')
const grandTotalEl = document.getElementById('grandTotal')
const inputEls = tableEl.querySelectorAll('input[name=quantity]')
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();
?>