基本Jquery / Javascript计算

时间:2011-10-06 04:27:39

标签: javascript jquery calculator

我做了一个我计算的表格。如果我制作这个PHP就不那么难了。但是我打算把它变成Jquery或JavaScript,所以无论谁将数字放入其中,它都可以立即计算出来,他们不必点击任何按钮。有没有人可以帮我这个?

http://jsfiddle.net/gXYg5/

1 个答案:

答案 0 :(得分:3)

好的,我写了这个,你可以在这里看到它:http://jsfiddle.net/jfriend00/b9dUn/

这是代码的样子。代码本来可以更紧凑,但由于你没有有意义的字段名,我使用了很多中间局部变量来使代码更具可读性。

$("#calc").click(function() {
    var salesPrice = getNum("textfield");
    var tradeIn = getNum("textfield2");
    var subTotal1 = salesPrice - tradeIn;
    setNum("textfield3", subTotal1, "dollar");

    var docFee = getNum("textfield4");
    var subTotal2 = docFee + subTotal1;
    setNum("textfield5", subTotal2, "dollar");

    var salesTax = getNum("textfield6", "percent");
    var license = getNum("textfield7");
    var subTotal3 = (subTotal2 * (1 + salesTax)) + license;
    setNum("textfield8", subTotal3, "dollar");

    var cashDown = getNum("textfield9");
    var rebate = getNum("textfield10");
    var amountFinanced = subTotal3 - cashDown - rebate;
    setNum("textfield11", amountFinanced, "dollar");

    var interestRate = getNum("textfield12", "percent");
    var term = getNum("textfield13");

    var payment = (amountFinanced * interestRate) / (1 - Math.pow(1 + interestRate, -term));
    setNum("textfield14", payment, "dollar");

});

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function getNum(id, type) {
    try {
        var raw = document.getElementById(id).value;
        raw = raw.replace(/\$|\s|%|,/g, "");
        raw = Number(raw);
        if (isNaN(raw)) {
            raw = 0;
        }
        if (type === "percent") {
            raw = raw / 100;
        }
        return(raw);
    } catch(e) {
        return(0);
    }
}

function setNum(id, val, type) {
    if (type === "dollar") {
        val = val.toFixed(2);
        val = "$" + addCommas(val);
    } else if (type === "percent") {
        val = (val * 100).toFixed(2) + "%";
    }
    document.getElementById(id).value = val;
}

// fill in some default values for testing:
setNum("textfield", 20000, "dollar");  // sales price
setNum("textfield2", 5000, "dollar");  // tradein
setNum("textfield4", 12, "dollar");  // doc fee
setNum("textfield6", 0.075, "percent");  // sales tax
setNum("textfield7", 75, "dollar");  // license
setNum("textfield9", 20, "dollar");  // cash down
setNum("textfield10", 40, "dollar");  // rebate
setNum("textfield12", 0.035, "percent");  // interest rate
setNum("textfield13", 72);  // month term

如果您为字段提供了有意义的名称,例如id="cashDown"而不是id="textfield9",那么编码将会少得多。我从here获得了贷款支付公式。您应该验证它对您来说是否正确。我只是对计算字段进行了读取,因此无法通过键入操作它们,我给它们一个不同的颜色,这样你就可以在点击计算按钮后更容易地看到它们。

我没有仔细检查这一点,以确保计算的每个部分都正确,并且所有输入错误处理都是所需的。你应该这样做,让你满意。这应该可以让您了解如何执行此操作。