简体   繁体   中英

Add two or more form values to get a grand total

This JavaScript function works independently for each line in the php foreach loop below just fine. However I Want to add those two independent totals together to get a grand total and display it in the DIV tag below. I can't figure out how to set aside the amounts and then add them together. The grand total should update with each change of quanity just like the amounts currently do. Right now totalprice just reflects one amount but not a grand total.

<head>
<script type="text/javascript">
function update(iteration){


var qty = document.getElementById('qty_' + iteration).value;
// alert('quantity_' + iteration);

var price = document.getElementById('price_' + iteration).value;
price = price.substring(0, 7);
qty = parseInt(qty);

var amount = (qty * price).toFixed(2) ;
parseFloat(document.getElementById('amount_' + iteration).value = amount).toFixed(2);


//HERE's the code that's not working..
var subtotal;
for(var i =1; i < itemCount; i++) {
subtotal += document.getElementById('amount_' + i).value;
}


//this works
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total $"+parseFloat(subtotal);

}
</script>
</head>


<?php

$listitems = unserialize($row["products"]);
    $i=1; 
        foreach($listitems as $item)
        {
        echo '<tr><td>'.$item["code"].'</td><td><input type="number" id="qty_'.$i.'" name="qty_'.$i.'"  min="1" size="3" value="1" onChange="iteration = '.$i.'; update(iteration); " /></td>';
        echo '<td><input type="hidden" name="price_'.$i.'" id="price_'.$i.'"  value="';
        echo $item['price'];
        echo '" />';
        echo $item['price'];
        echo '</td><td><input type="text" name="amount_'.$i.'" id="amount_'.$i.'" size="6" readonly value="';
        echo $item['price'];
        echo '"/></td></tr>';
    $i++;
    }


?>


<div id="totalPrice"></div>

Couple things stick out.

parseInt( ) needs a radix parameter.

parseInt(qty, 10);

Im confused on what this line is doing:
parseFloat(document.getElementById('amount_' + iteration).value = amount).toFixed(2);

parseFloat returns a floating point, but you arent setting it to anything?

The problem that is causing your error is the var subtotal declaration.

You are declaring a variable to equal amount + itself , which doesn't exist yet. What do you want subtotal to equal?

Edit: Now that you updated, you want to iterate the number of items and add them all together.

var subtotal;
for(var i =0; i < itemCount; i++) {
  subtotal += document.getElementById('amount_' + i).value;
}

This would iterate over 0-itemCount of the amount elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM