-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
55 lines (48 loc) · 1.7 KB
/
app.js
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
'use strict';
// Amount of bill input
const billInput = document.querySelector('#bill-amount');
// Tip % input
const rateService = document.querySelector('#select-service');
// Amount of people paying the bill
const splitAmount = document.querySelector('#split-amount');
// Calculate button
const calculateBtn = document.getElementById('calc-btn');
// Final message (after calc)
const outputMessage = document.getElementById('message-display');
// Hide visibility of final output message
outputMessage.style.display = 'none';
function calculateTip() {
// Show alert if any of the fields is missing a value
if (
billInput.value === '' ||
splitAmount.value === '' ||
rateService.value === 0
) {
alert('All fields required');
} else {
// display results message once all fields meet criteria
outputMessage.style.display = 'block';
}
// Convert each input value to a decimal number
const people = parseFloat(splitAmount.value);
const billAmount = parseFloat(billInput.value);
const serviceQuality = parseFloat(rateService.value);
// Will disappear the -each- span if only 1 person pays
if (people <= 1) {
document.getElementById('each').style.display = 'none';
} else {
document.getElementById('each').style.display = 'block';
}
// Amount to pay (each)
const amountEach = document.getElementById('total-amount');
// Get percentage
const tip = billAmount * serviceQuality;
// Add percentage to bill amount
let billPlusTip = billAmount + tip;
// Divide by amount of people paying
let total = billPlusTip / people;
// Will only show 2 decimal places
total = total.toFixed(2);
amountEach.innerHTML = total;
}
calculateBtn.addEventListener('click', calculateTip);