0

I'm building a simple checkout page with on the left side a box with the prices and on the right the payment form. I'm trying to get the cart total to also print on an input field in the payment form. I tried to change the id cartTotal for a class so that the input field can also have the class "cartTotal". Doing so just mess with the entire script. The numbers wont show up.

ApplyTax Script:

<script>
    function applyTax() {
        var cartSubTotal = parseFloat(document.getElementById('cartSubtotal').innerHTML);
        console.log(cartSubTotal);
        var salesTaxGst = (cartSubTotal / 100) * 5;
        var salesTaxPst = (cartSubTotal / 100) * 9.975;
        var totalAmount = (cartSubTotal * 1) + (salesTaxGst * 1) + (salesTaxPst * 1);

        document.getElementById('cartSubtotal').innerHTML = cartSubTotal.toFixed(2);
        document.getElementById('taxGst').innerHTML = salesTaxGst.toFixed(2);
        document.getElementById('taxPst').innerHTML = salesTaxPst.toFixed(2);
        document.getElementsByClassName('cartTotal').innerHTML = totalAmount.toFixed(2);
    }

    // Call the applyTax() when the window finishes loading...
    window.onload = function() {
        applyTax();
    }
</script>

The Payment Form:

<form method="post" action="purchase" name="checkout">
    Total &nbsp; &nbsp;
    <input maxlength="6" type="text" class="cartTotal" name="x_amount" size='9' readonly value="${cart.total}" />
    <br>
    <br>
    <p>
        <fmt:message key='CreditNumber' />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </big><big><br>
  <input maxlength="20" size="30" name="cc_number"></big>
        <br>
        <br>
        <big><fmt:message key='NameCard'/>&nbsp;&nbsp;&nbsp;&nbsp; </big><big><br>
</form>

This not work, the fields return blank, what am I doing wrong?

Community
  • 1
  • 1
user45678
  • 343
  • 2
  • 6
  • 19
  • 4
    Because you have to iterate over each of the elements in the NodeList returned from `getElementsByClassName()` to set their individual properties (and that's true whether there's one element, or multiple, in the NodeList). – David Thomas May 07 '15 at 20:57
  • 1
    `getElementsByClassName` returns a list of all the elements with that class (that's why the name has a plural in it). You have to set the inner HTML of each of them separately, with `for` loop. – Barmar May 07 '15 at 21:04
  • @Barmar: Thank you for forwarding me to the right place. But I just changed my script to: `var elements = document.getElementsByClassName( 'cartTotal' ).innerHTML = totalAmount.toFixed(2); for(var i = 0; i < elements.length; i++) { elements[i].innerHTML = totalAmount.toFixed(2); } }` No number shows up... `:/` – user45678 May 07 '15 at 21:26
  • 1
    Get rid of everything from `.innerHTML` on the first line. – Barmar May 07 '15 at 21:28

0 Answers0