JS函数,用于计算产品数量和选项附加税

JS function that calculates products qty and options additional taxes

本文关键字:选项 附加税 函数 用于 计算 JS      更新时间:2023-09-26

我有一个复杂的JS函数,它必须计算产品单个价格*数量的总和,如果产品有可用的选项,如果可用的选项有额外的税,它也必须添加到总数中。

function update_amounts() {
    var sum = 0.0;
    $('#basketorder > tbody  > .product').each(function () {
        var qty = $(this).find('.qty option:selected').val();
        var selectedoptaddtax = 0.0;
        $('.selectedoptionselect option:selected').each(function () {
            var selectedoptaddtax = $(this).attr('price');
        })
        var price = $(this).find('.price').val();
        var amount = ((qty * price) + selectedoptaddtax);
        sum += amount;
        $(this).find('.amount').text('' + amount);
    });
    $('.total').text(sum);
}

我在这里准备了jsfiddle

在这个例子中,我的篮子里只有1个产品,但如果篮子里有1个以上的产品,函数必须计算正确。

$(document).ready(function () {
    update_amounts();
    $('.qty').change(function () {
        update_amounts();
    });
    $('.selectedoptionselect').change(function () {
        update_amounts();
    });
});

您需要添加选定的选项价格。

代码

$(document).ready(function () {
    $('.selectedoptionselect, .qty').change(function () {
        update_amounts();
    }).change();
});
function update_amounts() {
    var sum = 0.0;
    $('#basketorder > tbody  > .product').each(function () {
        var qty = $(this).find('.qty').val();
        var selectedoptaddtax = 0.0;
        //Use find here
        $(this).find('.selectedoptionselect option:selected').each(function () {
            selectedoptaddtax += +$(this).attr('price'); // You need to add price
        })
        var price = $(this).find('.price').val();
        var amount = (qty * price) + (qty * selectedoptaddtax); //Changes here
        sum += amount;
        $(this).find('.amount').text('' + amount);
    });
    $('.total').text(sum);
}

DEMO