Reputation: 99
I'm working on an online orderform using javascript. I almost have it working, but what I would like to do is apply a 12.5% discount if more than 5 items are selected. So far I have managed to get the discount to apply if more than any one item is selected. Here is my code:
var totalItems = 0
// Run through the form fields to check for any filled fields
for (var i=0; i<juiceForm.length; i++)
{
n=0;
juicetotal = 0;
itemQuantity = Number(parseInt(juiceForm[i].value)); // convert field value to a number
itemQuantity = parseInt(juiceForm[i].value);
if (isNaN(itemQuantity))
{
itemQuantity = 0; // If the form field value is not a number, make it zero
}
// count the total number of juices selected
totalItems = totalItems += Number(parseInt(juiceForm[i].value));
if (totalItems >= 5 || itemQuantity >= 5 || (totalItems + itemQuantity) >= 5)
{
juiceTotal = (juiceTotal+(itemQuantity * juicePrice[i]))*0.875;
}
else
{
// Multiply the quantity by the item price and update the order total
juiceTotal = juiceTotal+(itemQuantity * juicePrice[i]);
}
}
Where I'm running into trouble is if multiple items are selected giving a total of more than 5 items, the calculation is coming out wrong. For example, if I have 5 crates of apple juice at £20 and 1 crate of orange at £22, with a 12.5% discount I should be getting a total of £106.75 but I am getting £95.81.
I'm not sure if I have made an obvious mistake. Can anyone give me any advice on what I'm doing wrong?
Upvotes: 0
Views: 1097
Reputation: 2423
Maybe you think of this (not tested, take it as pseudocode)
var totalItems = 0
var juiceTotal = 0;
for (var i=0; i<juiceForm.length; i++)
{
var itemQuantity = parseInt(juiceForm[i].value);
if (isNaN(itemQuantity))
{
itemQuantity = 0;
}
totalItems += itemQuantity;
juiceTotal += (juicePrice[i]*itemQuantity);
}
if (totalItems >= 5)
juiceTotal *= 0.875;
}
Upvotes: 1