0

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();
?>
2
  • 2
    Oops, that's not the problem! You are not calling calTotal you are just defining it :) Commented May 22, 2019 at 21:48
  • How can i call it as soon as my script launches? Commented May 22, 2019 at 21:50

2 Answers 2

2

Try wrapping your function with

(function calTotal() { 
    //...contents
})();

Which will convert the function definition to IIFE, and your event listeners will be bound.

What is the (function() { } )() construct in JavaScript?

Or just add calTotal(); just before </script>

and move these lines into the event handler, or make them globally accessible:

const grandTotalEl = document.getElementById('grandTotal')
const inputEls = tableEl.querySelectorAll('input[name=quantity]')

Ok, change your code like this:

<script> 
    function calTotal() {
        const updateGrandTotal = () => {
            const tableEl = document.getElementById('articles')
            const grandTotalEl = document.getElementById('grandTotal')
            const inputEls = tableEl.querySelectorAll('input[name=quantity]')
            grandTotalEl.innerText = inputEls.reduce((total, inputEl) => {
                const maxQuantity = parseInt(inputEl.dataset.maxQuantity)
                if(parseInt(inputEl.value) > maxQuantity) inputEl.value = maxQuantity
                else 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)
        }

        quantityInputEls.forEach(el => el.addEventListener('keyup', () => updateGrandTotal(grandTotalEl, inputEls)))
    };
</script>

Then you can debug it at your developer tools window to see what's not working.

Sign up to request clarification or add additional context in comments.

2 Comments

Well now my console log work but it still doesn't give me the total. Do you have any idea what's wrong with my code?
I put these lines before the calTotal, but it still doesn't return the total. I can't seem to find the error in my code
0
// Create javascript-only function for loaded DOM
function readyFired(callback) {
    document.readyState != 'complete' ? setTimeout('readyFired(' + callback + ')', 1) : callback();
}

// DOM is fully-loaded and ready to calculate the total
readyFired(function() {
    calTotal();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.