Link to home
Create AccountLog in
Avatar of MJ
MJFlag for United States of America

asked on

JavaScript How to Add Up Prices?

I'm trying to add all the values from a <p> tag for a total. Not sure what I'm doing wrong?
<HTML>
<body>

<p class="align-self-end account-paragraph">$250.10</p>

<p class="align-self-end account-paragraph">$25.34</p>

<p class="align-self-end account-paragraph">$50.07</p>

<p class="align-self-end account-paragraph">$75.42</p>

<script>

function _dtmGetFundingAmt() {
    var arr_p = document.querySelectorAll("p");
    var element = null;
    var totalFundingAmt = 0.00;
    for (var i = 0; i < arr_p.length; i++) {
        if (arr_p[i].textContent.replace(/^\s+|\s+$/g, "").indexOf("$") >= 0) {
            element = arr_p[i];
            var elemVal = element.textContent;
            elemVal = elemVal.replace(/\$/g, '');
            elemVal = parseInt(elemVal);
            elemVal = elemVal.toFixed(2);
            totalFundingAmt += elemVal;
            console.log("totalFundingAmt : " + totalFundingAmt);
        }
    }

    return totalFundingAmt;
};


var total = _dtmGetFundingAmt();
console.log("#### results : " + total);

</script>
</body>
</html>

Open in new window

Thanks!
ASKER CERTIFIED SOLUTION
Avatar of David S.
David S.
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account