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)それを出力するコードの部分でのみ使用する必要があります。この場合、のような構造を持ち、余分なs$("#someID").html(total.toFixed(2))を削除する必要があります。parseFloat()このようなもの:

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 に答える