以下javascript代码根据数量计算产品重量和成本,并发送ajax请求以根据重量获取运输成本。数量可以由用户更改。变量totalWeight被设置为Nan,但这并不是每次都发生。我需要帮助来找到为什么将totalWeight设置为Nan。
下面是代码
var totPkgs = parseInt(26);
$(".Update").click(function () {
var totalpkgs = 0;
var totalWeight = 0;
var totalCost = 0;
var foodCost = 0;
var petQtys = 0;
var qtys = $("input[name='qty']"); //type="number"
var fPrice = $("input[name='foodPrice']"); //type="hidden"
var mainDiv = $(this).parent().parent().parent();
var petType = $(this).data("pettype");
var spanWeight = $("span[data-pettypew='" + petType + "']");
var petWeight = $("span[data-pettypeq='" + petType + "']")
var petQty = $("input[data-pettypeq='" + petType + "']");//type="number"
var weeks = $("#interval").val();//select
for (var i = 0; i < qtys.length; i++) {
var pkgs = parseInt($(qtys[i]).val());
totalpkgs = totalpkgs + pkgs;
var cost = parseFloat($(fPrice[i]).val()) * 2;
var tcost = parseFloat(cost * pkgs).toFixed(2);
foodCost = parseFloat(foodCost) + parseFloat(tcost);
}
for (var a = 0; a < petQty.length; a++) {
petQtys = parseInt(petQtys) + parseInt($(petQty[a]).val());
}
foodCost = parseFloat(foodCost).toFixed(2);
totalWeight = totalpkgs * 2;
if (totalpkgs != totPkgs) {
alert('This is now different than the recommended amount to feed. Are you sure you want to do this?');
}
if (totalpkgs < 10) {
alert('This amount is below our 20 lb. minimum order. Please increase your order amount. You can reduce the amount fed per week by increasing the number of weeks between orders (shipping frequency link on the right)');
$("#AddToCart").remove();
} else {
if ($("#AddToCart").length == 0) {
$(".bott-links2").append("<input type='submit' class='btn' value='Add to Cart' id='AddToCart' />");
}
}
$.ajax({
url: '/UpdateQty',
type: "POST",
data: { weight: totalWeight },
success: function (result) {
var shipCost = parseFloat(result);
totalCost = parseFloat(parseFloat(foodCost) + parseFloat(shipCost)).toFixed(2);
var discCost = totalCost - (totalCost * @Model.discountPercen / 100);
$(".totalPrice").text("$" + totalCost);
$(".discCost").text("$" + discCost.toFixed(2));
$("input[name='price']").val(totalCost);
$(spanWeight).text(parseFloat(petQtys * 2));
$(petWeight).text(parseFloat(petQtys));
var perWeek = parseFloat(totalCost / weeks).toFixed(2);
$("#weekCost").text(perWeek);
},
error: function (result) {
alert("error");
}
});
mainDiv.find(".editable ").css("display", "none");
mainDiv.find(".meatDetails").css("display", "block");
$(this).css("display", "none");
$(this).parent().find("a").css("display", "block");
});