I am trying to create a script which automatically shows a price depending on the entered value.
My price discounts could be:
1 item or more = "£5";
5 items or more = "£30";
10 items or more = "£55";
So when the user types “7” in an input box, the price is displayed as £30*7.
The only way I know how to do this is by making an if else statement for each case, but I am guessing there’s an easier way?
This is my pseudo code:
<script>
function calc() {
var amountVar = document.getElementById('amount').value;
var discount = new Array();
discount[1] = "£5";
discount[5] = "£30";
discount[10] = "£55";
match = discount where amountVar matches key or more;
document.getElementById('price').innerHTML = match;
}
</script>
<input onkeyup="calc();" id="amount">
<br>
Price: <p id="price"></p>
Rather than an
if/else, you can put them all in an array and just go through the array in aforloop until you find the matching discount. This has several advantages, the main one being that it’s trivial to edit the discounts array without writing new code.