Reputation: 341
For the life of me I can't seem to figure out why this function won't calculate correctly. If I run this function the discount (totalPrice
) is applied twice, for example: 20*1.05 == 21
, but when the function runs and it gives me 22.05
.
What am I doing wrong? Thanks for the help.
<script type="text/javascript">
function codeDiscount() {
var totalCost = document.getElementById('total').value;
var custCode = document.getElementById('coupon').value;
if (custCode == "ABCD" || custCode == "EFGH")
{
totalCost = document.getElementById('total').value;
var totalPrice = parseInt(totalCost) * 1.05;
document.getElementById('total').value = totalPrice;
}
}
</script>
Upvotes: 0
Views: 326
Reputation: 173542
If your total field is being updated every time something changes, it's better to adopt this:
Store the total value in a separate variable:
var cartTotal = 0;
Then, whenever the sum of items changes, you update it:
// calculate sum of all products
cartTotal = 0;
for (var i in all_products) {
cartTotal += all_procucts[i].price;
}
// calculate discount
codeDiscount();
To recalculate discount you use the cartTotal
but you only update the field
var totalPrice = cartTotal;
if (custCode == 'ABCD') {
totalPrice *= 1.05;
}
document.getElementById('total').value = totalPrice;
Upvotes: 0
Reputation: 166
I suspect that the problem isn't in this code block. Is there anything that would cause codeDiscount() to be called a second time?
Upvotes: 1
Reputation: 21
I suspect there is something wrong with ur code:
<script type="text/javascript">
function codeDiscount() {
var totalCost = document.getElementById('total').value;
var custCode = document.getElementById('coupon').value;
if (custCode == "ABCD" || custCode == "EFGH")
{
var totalPrice = parseInt(totalCost) * 1.05;
document.getElementById('total').value = totalPrice;
}
}
</script>
Also, please make sure that you don't call the same function twice. Otherwise, the result will be incorrect.
Upvotes: 0