0

我有一个表单,它从输入字段和下拉列表中输出计算。

除了总数之外,脚本还不错。当您输入一个数字并从下拉列表中选择一个值时,在 html 中总计将四舍五入到小数点后 2 位。

谁能明白为什么会这样?

表格如下:

<input type="text" name="amount" id="amount" maxlength="6" autocomplete="off"/><span class="paymentalert" style="color:red;"></span>
<br /><br />
<label for="delivery">Delivery:</label>
<select id="delivery" name="delivery">
    <option value="1.50">Fast</option>
    <option value="2.50">Medium</option>
    <option value="3.50">Slow</option>
</select>

javascript如下:

function updateCost()
{
    var amount = parseFloat($('#amount').val()).toFixed(2);
    var delivery = parseFloat($('#delivery').val()).toFixed(2);   

    var total = parseFloat(amount) + parseFloat(delivery);
    $("#total").html(total);
    $("#amountdiv").html(amount);
    $("#deliverydiv").html(delivery);

    var fixedrate =  parseFloat(total / 100 * 8.2).toFixed(2);

    var grandtotal = parseFloat(fixedrate) + parseFloat(total);
    $("#grandtotal").html(grandtotal);
    $("#total").html(total);
    $("#fixedrate").html(fixedrate);    

}

$(document).ready(function(){
    $('#amount').change(function(){ updateCost(); });
    $('#delivery').change(function(){ updateCost(); });
    $('#grandtotal').change(function(){ updateCost(); });
}); 
4

1 回答 1

3

toFixed(2)只应在输出它的代码部分中使用。在这种情况下,您应该有类似 , 的结构$("#someID").html(total.toFixed(2)),并删除多余parseFloat()的 s。像这样的东西:

function updateCost() {
    var amount = parseFloat(document.getElementById("amount").value),
        delivery = parseFloat(document.getElementById("delivery").value),
        total = amount + delivery,
        fixedrate =  total / 100 * 8.2,
        grandtotal = fixedrate + total;

    document.getElementById("total").innerHTML = total.toFixed(2);
    document.getElementById("amountdiv").innerHTML = amount.toFixed(2);
    document.getElementById("deliverydiv").innerHTML = delivery.toFixed(2);
    document.getElementById("grandtotal").innerHTML = grandtotal.toFixed(2);
    document.getElementById("fixedrate").innerHTML = fixedrate.toFixed(2);
}

$(function(){
    document.getElementById("amount").onchange =
        document.getElementById("delivery").onchange = updateCost;
}); 
于 2013-03-06T22:36:57.650 回答