javascript 101:销售税计算器不响应数据输入

时间:2014-09-19 01:28:03

标签: javascript calculator

我猜测onload功能没有正确实现。输入数字或字母不会得到相应的错误或计算响应。

这是我现在的代码:

http://jsfiddle.net/907yn57r/

var $ = function (id) {
    return document.getElementById(id);
}
var calculateTaxAndTotals = function () {
    var taxRate = parseFloat($("taxRate").value); //The tax rate, as a percentage (e.g. 8.5)
    var subTotal = parseFloat($("itemPrice").value); //An item price ex $5.95

    $("salesTax").value = "";
    $("totalItemCost").value = "";

    if (isNaN(taxRate) || taxRate <= 0) {
        document.taxCalc.taxRate.focus();
        document.$("taxRateMessage").firstChild.nodeValue = "Please enter a valid value.";
    } else if (isNaN(itemPrice) || itemPrice <= 0) {
        document.$("priceMessage").firstChild.nodeValue = "Please enter a valid value.";
    } else {
        var salesTax = subTotal * (taxRate / 100);
        var totalItemCost = salesTax + itemPrice;
        $("orderTotal").focus();
        alert(totalItemCost);
    }

}

window.onload = function () {
    calculateTaxAndTotals();
}

1 个答案:

答案 0 :(得分:0)

有几个问题。

首先,JSFiddle处理主要的html结构本身,因此您不需要新的body标签等。

其次,这里的Javascript需要加载到头部或正文中(在JSFiddle的左上角,您可以选择不同的位置来加载它)。

最后,CalculateTaxAndTotals的定义中有一些错误,应该说

if (isNaN(taxRate) || taxRate <= 0) {
        document.taxCalc.taxRate.focus();
        $("taxRateMessage").firstChild.nodeValue = "Please enter a valid value.";
    } else if (isNaN(subTotal) || itemPrice <= 0) {
        $("priceMessage").firstChild.nodeValue = "Please enter a valid value.";
    } else {
        var salesTax = subTotal * (taxRate / 100);
        var totalItemCost = salesTax + itemPrice;
        $("orderTotal").focus();
        alert(totalItemCost);
    }

Really Fixed Fiddle

最后一个问题是您在isNaN上呼叫itemPrice,但变量itemPrice并不存在。

相关问题