I'm creating a page where users can purchase an adult, child or senior ticket, each with it's own pricing.
Here's the code for review. Please let me know if there are ways to improve upon this code.
// declare all variables
var adultQty = document.getElementById('quantityAdult');
var childQty = document.getElementById('quantityChild');
var seniorQty = document.getElementById('quantitySenior');
var submitBtn = document.getElementById('submitButton');
var outputPara = document.getElementById('totalPrice');
// generic function that takes in quantity and multiplies with appropriate price
function calcPrice(qty, price){
return qty * price;
}
// generic function that outputs final price and amout it tickets purchased
function getMessage(qty, total){
return outputPara.innerHTML = 'You purchased ' + qty + ' ticket(s) and your total price is $' + total + '<br><br>' + '<button>Proceed To Checkout</button>';
}
submitBtn.addEventListener('click', function() {
if(adultQty.value === '0' && childQty.value === '0' && seniorQty.value === '0'){
alert('Please purchase at least 1 ticket');
} else {
var totalAdult = calcPrice(adultQty.value, 49);
var totalChild = calcPrice(childQty.value, 20);
var totalSenior = calcPrice(seniorQty.value, 30);
var totalPrice = totalAdult + totalChild + totalSenior;
var totalTix = parseInt(adultQty.value) + parseInt(childQty.value) + parseInt(seniorQty.value);
getMessage(totalTix, totalPrice);
}
});
<p>Purchase your tickets online! </p>
<ul>
<li>$49 - Adult</li>
<li>$20 - Child</li>
<li>$30 - Senior </li>
</ul>
<label>Quantity: </label><input type="text" id="quantityAdult" value="0"> <label>Adult</label>
<br><br>
<label>Quantity: </label><input type="text" id="quantityChild" value="0"> <label>Child</label>
<br><br>
<label>Quantity: </label><input type="text" id="quantitySenior" value="0"> <label>Senior</label>
<br><br>
<button type="submit" id="submitButton">Submit</button>
<p id="totalPrice"></p>