使用价格更新购物车,如果subTotal超过$40,则提供优惠券



正在做一个学校评估测试的基本HTML设计。我想添加一个功能,当您提交数量时,它将更新购物车小计,如果小计大于40,它将给出一个提示折扣代码的警报。我是新的javascript和编码在一般情况下,所以我挣扎大时间。我觉得我很接近,但得到'NaN',我认为这是因为id=quantity没有被输入到函数中。

为了作业的目的,我不想使用jquery, php也不是必需的。

相关html:

<div id="quantity">
<h4>How many people are coming?</h4>
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity" pattern="[0-9]+" onchange="cartUpdate()" >
</div>  
<div id="cart">
<p>Total Cost: <span id="subTotal"></span></p>
<button id="submit" type="submit" value="Order">Submit Order</button>
</div>

javascript:

var quantity = document.getElementById("quantity").value;

function cartUpdate() {
var subTotal = (15 * quantity).toFixed(2) - 0 ; 
document.getElementById("subTotal").innerHTML = "$" + subTotal;
}
document.getElementById("submit").addEventListener("click", function() { 
if (subTotal > 40) {
alert("Your ticket has been sent to your email. Since you have spent over $40, you are also eligible for a 20% off coupon for the snack bar which is included in your ticket.")
}});

它给你NaN而不是total,因为你已经将quantity的值存储在程序启动时的undefined页面加载上。要解决这个问题,每次值更改时获取最新的值。看看下面的代码,它会像你期望的那样工作。

var quantity = document.getElementById("quantity").value;
var subTotal = 0;
function cartUpdate(e) {
subTotal = (15 * e.target.value).toFixed(2) - 0;
document.getElementById("subTotal").innerHTML = "$" + subTotal;
}
document.getElementById("submit").addEventListener("click", function() {
if (subTotal > 40) {
alert(
"Your ticket has been sent to your email. Since you have spent over $40, you are also eligible for a 20% off coupon for the snack bar which is included in your ticket."
);
}
});
<div id="quantity">
<h4>How many people are coming?</h4>
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity" pattern="[0-9]+" onchange="cartUpdate(event)" />
</div>
<div id="cart">
<p>Total Cost: <span id="subTotal"></span></p>
<button id="submit" type="submit" value="Order">Submit Order</button>
</div>

最新更新