Javascript 输入值赢得';t在事件发生后更新,即使达到功能
我有一个HTML表单,我正在用vanilla javascript验证它。 到目前为止,没有一个领域提出任何问题。我可以使用计算值正确更新表单字段。除了我用来显示采购小计的字段 我不知道为什么它不让我特别更新这个字段。我看不出代码有任何错误,对于console.log(),我可以确认是否达到了更新值的函数。 在某些情况下,即使在事件结束后,我也会再次记录该值,结果仍然良好。我不知道为什么它没有出现 最重要的是:将值记录在浏览器控制台上会显示该值符合预期,但字段本身仍然不会显示该值 html:Javascript 输入值赢得';t在事件发生后更新,即使达到功能,javascript,html,validation,Javascript,Html,Validation,我有一个HTML表单,我正在用vanilla javascript验证它。 到目前为止,没有一个领域提出任何问题。我可以使用计算值正确更新表单字段。除了我用来显示采购小计的字段 我不知道为什么它不让我特别更新这个字段。我看不出代码有任何错误,对于console.log(),我可以确认是否达到了更新值的函数。 在某些情况下,即使在事件结束后,我也会再次记录该值,结果仍然良好。我不知道为什么它没有出现 最重要的是:将值记录在浏览器控制台上会显示该值符合预期,但字段本身仍然不会显示该值 html: 我
我没有这些ID/类的CSS规则,所以我知道我没有在上面隐藏或写东西。请编辑您的问题并创建一个代码段(单击
符号),以便我们可以使用您的代码。为什么有只读元素?这个问题需要他们吗?如果否,则删除它们您的表单
和输入
元素的ID都是“小计”
。控制台日志subtotalField
内部calculateSubtotal()
的简单健全性检查可立即识别问题。还有一个问题是,对正在运行的折扣总额使用两个变量名。
<section>
<form>
<label for="inpPrice">Unit Price</label>
<input type="number" id="inpPrice" name="inpPrice" readonly>
<label for="inpAmount">Amount</label>
<input type="number" id="inpAmount" name="inpAmount">
<label for="showDiscount">Discount</label>
<input type="number" id="showDiscount" name="showDiscount">
<button type="button" id="btnValidateForm" onclick="validateForm()">Add to Cart</button>
</form>
</section>
<section>
<form id="subtotal">
<div id="shoppingCart">
</div>
<label for ="runningTotal">Total for this purchase</label>
<input type="number" readonly id="runningTotal">
<label for="applicableDiscount">Applicable Discount</label>
<input type="number" readonly id="discountRunningTotal">
<label for="subtotal">Subtotal</label>
<input type="number" id="subtotal" readonly>
</form>
</section>
let runningTotal = 0;
let discountRunningTotal = 0;
const subtotalField = document.getElementById("subtotal")
const priceField = document.getElementById("inpPrice");
const amountField = document.getElementById("inpAmount");
const discountField = document.getElementById("showDiscount");
function validateForm(){
calculateTotal();
calculateTotalDiscount();
calculateSubtotal();
}
function calculateTotal(){
let unitPrice = parseInt(priceField.value)
let amount = parseInt(amountField.value)
runningTotal += unitPrice * amount;
}
function calculateTotalDiscount(){
discountRunningTotal += parseInt(discountField.value)
}
function calculateSubtotal(){
console.log("calculating final price...")
let finalPrice = 0;
finalPrice = runningTotal - runningDiscountTotal;
console.log(finalPrice);
subtotalField.value = finalPrice;
console.log("Value for subtotal is: ", subtotalField.value); //This ALWAYS shows the correct subtotal. It simply doesn't put the value in the subtotal field.
}