我已经得到了总价。问题是当我尝试更改以前的产品类型时,我的逻辑存在缺陷,价格仍在增加。这是我的错误示例。我可以'解释得很好,但我得到了一个有效的例子。
小提琴: Jsfiddle
代码:
jQuery(document).ready(function($) {
var sum = 0;
var price = 0;
var total = 0;
var documents = "Documents (Up to 1kg)";
var small = "Small (1-5kg 85cm)";
var medium = "Medium (5-10kg 110cm)";
function checkTotal() {
var qty = $("input[name*='qty']");
var piece_type = $("select[name*='piece_type']");
qty.each(function(index) {
var quantity = qty.eq(index).val();
var selected = piece_type.eq(index).find(":selected").text();
if (selected == documents) {
price = 10;
sum = parseFloat(quantity) * parseFloat(price);
}
if (selected == small) {
price = 20;
sum = parseFloat(quantity) * parseFloat(price);
}
if (selected == medium) {
price = 30;
sum = parseFloat(quantity) * parseFloat(price);
}
if(selected == selected){
total += sum;
}
$("#wpc_total").text("Total : $" + total);
});
}
$("select[name*='piece_type']").change(checkTotal);
});
答案 0 :(得分:1)
每次更改值时计算总数:
jQuery(document).ready(function($) {
var price = 0;
var documents = "Documents (Up to 1kg)";
var small = "Small (1-5kg 85cm)";
var medium = "Medium (5-10kg 110cm)";
function checkTotal() {
var qty = $("input[name*='qty']");
var piece_type = $("select[name*='piece_type']");
var total = 0;//local total changes every time you change the values
qty.each(function(index) {
var sum = 0;//reset the sum to 0
var quantity = $(this).val()? $(this).val():0;
var selected = piece_type.eq(index).find(":selected").text();
if (selected == documents) {
price = 10;
sum = parseFloat(quantity) * parseFloat(price);
}
if (selected == small) {
price = 20;
sum = parseFloat(quantity) * parseFloat(price);
}
if (selected == medium) {
price = 30;
sum = parseFloat(quantity) * parseFloat(price);
}
total += sum;//no need for a if
});
$("#wpc_total").text("Total : $" + total);//show the total after the loop
}
$("select[name*='piece_type'],.number").change(checkTotal);
});