Update working prices but not with several select and discount the price at the end

advertisements

I have multiple dropdown lists calculating a total price at the end, it works great apart from a few issues.

Firstly, I would like to add further prices to it, so it should read:

Total : £20.97

V.A.T : £4.19

Total Amount : £25.16

I'm sure this is simple but i cannot think how?

Secondly - It only works on a single selection drop down lists, if i want to select multiple options in one list, it will only calculate one

Here's the code i use to calculate the price:

$(function(){
    $(".calculate").on("change", function(){
        var total = 0;
        $('.calculate').each(function() {
            if($(this).val() != 0) {
                total += parseFloat($(this).val());
            }
        });
        $('#total').text('£' + total.toFixed(2));
    });

});//]]>

Thirdly, there are about 8 dropdown lists but i want the last one to discount the total price instead of adding to it, the code above takes the price from option value of each selection and so will the discount amount (In the discount column in the database, it's written as 10%.

So basically, after 7 lists i should have a total of i.e. £20.97 then once the last list is selected, it should replace the price with a discount amount i.e. (-10%) £18.87

I'm so close to finishing this but i can't get over the last hurdle.

Thanks


When a SELECT allows multiple selections the jQuery val() function returns an array of values. So your code needs to detect if val() returns and array and if so loop the array and add all those items. Here is one way:

$('.calculate').each(function() {
    var currentValue = $(this).val();
    if (currentValue.length != undefined) {
        for (var i = 0; i < currentValue.length; i++) {
            if (currentValue[i] != 0) {
                total += parseFloat(currentValue[i]);
            }
        }
    }
    else if(currentValue != 0) {
        total += parseFloat(currentValue);
    }
});

That should take care of multiple select options. For the discount, just get the value of your final SELECT and apply your discount:

var discount = parseFloat($('.discount').val()) / 100;
total = total - (total * discount);