我有一个从输入字段和下拉输出计算的表单。
除了总计之外,剧本很好。当您键入图形并从下拉列表中选择一个值时,总计将四舍五入到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(); });
});
答案 0 :(得分:3)
toFixed(2)
只应在输出它的代码部分中使用。在这种情况下,您应该拥有$("#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;
});