/
tip_calculator.html
92 lines (78 loc) · 2.8 KB
/
tip_calculator.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<!DOCTYPE html>
<html>
<head>
<title>#4 projekt, tip calculator</title>
</head>
<body>
<h1>Cost of your receit: <span id="bill"></span></h1>
<h1>Your tip<span id="tip"></span></h1>
<h1>Total amount to pay: <span id="total" style="color: green"></span></h1>
<!-- 1. Create a simple tip calculator
2. It needs to accept 2 parameters
3. Make a tip parameter optional
4. Return the total amount and save it to a var -->
<script type="text/javascript">
//function to calculate tip based on bill and how much tip guest would like to leave [%]. There is an otpion to return total amount to pay
function calcTip(bill, tip_percent = 0, returnTotalAmount = false){
var tip = tip_percent/100 * bill;
var total = bill + tip;
if (returnTotalAmount){
return total;
}
return tip;
}
//function to check if the input is a number, and if so, it changes type of the user input from string to number
function checkIfNum(num){
num = Number(num);
if(isNaN(num)){
return false;
} else {
return num;
}
}
//function to obtaining element by Id
function $(id){
return document.getElementById(id);
}
// user cannot leave this loop unless his input is a number
while (true){
var bill = prompt("Please type the amount on your receit.");
if (checkIfNum(bill)){
bill = checkIfNum(bill);
break;
} else {
alert("You have to give a number")
}
}
// user cannot leave this loop unless his input is what we expect to be (sign "y" or "n" and then eventually a number)
while(true){
var answer = prompt("Would you like to give a tip? (Y/N)");
if (["y","n","Y","N"].includes(answer)){ //checking if user's input is a sing "y" or "n", casewise
answer = answer.toLowerCase();
if (answer == "y"){
var tenPercentTip = 0.1*bill;
tenPercentTip = tenPercentTip.toFixed(2); //rounding the number to the value coresponding with an actuall money
var tip_percent = prompt("How much of a tip would you like to give (in %)? (FYI 10% of your order equals to: "+ tenPercentTip);
if (checkIfNum(tip_percent)){ //checking, that if user want to give a tip, is it actually a number
tip_percent = checkIfNum(tip_percent);
break;
} else {
alert("You have to give a number")
}
} else {
break; //we leave the loop if user doesn't want to give a tip
}
} else {
alert("You have to type Y or N.")
}
}
var tip = calcTip(bill, tip_percent); //getting amount of tip using function
tip = tip.toFixed(2);
var total = calcTip(bill, tip_percent, true) // getting total amount to pay using fucntion with extra variable
//changing text on the website according to the user's input
$("bill").innerText = bill;
$("tip").innerText =" (" + tip_percent + "%): " + tip;
$("total").innerText = total;
</script>
</body>
</html>