Working on a school assessment testing basic HTML design. I want to add a function that when you submit a quantity it will update the cart subtotal, and if that subtotal is larger than 40 it will give an alert signifying a discount code. I am new to javascript and coding in general so am struggling big time. I feel like I am so close but getting 'NaN' which I assume is because the id=quantity is not being fed into the function.
For the purposes of the assignment I would like to not use jquery, and php is not necessary.
relevant 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.")
}});
It is giving you NaN instead of total because you have stored the value of quantity on a page load which is undefined at program start. To fix this get the latest value everytime value changes. See the code below it works as you expected.
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>