-
Notifications
You must be signed in to change notification settings - Fork 0
/
payments.js
71 lines (53 loc) · 2.06 KB
/
payments.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
let billAmtInput = document.getElementById('billAmt');
let tipAmtInput = document.getElementById('tipAmt');
let paymentForm = document.getElementById('paymentForm');
let paymentTbody = document.querySelector('#paymentTable tbody');
let summaryTds = document.querySelectorAll('#summaryTable tbody tr td');
let allPayments = {};
let paymentId = 0;
paymentForm.addEventListener('submit', submitPaymentInfo);
// Add a curPayment object to allPayments, update html and reset input values
function submitPaymentInfo(evt) {
if (evt) evt.preventDefault(); // when running tests there is no event
let curPayment = createCurPayment();
if (curPayment) {
paymentId += 1;
allPayments['payment' + paymentId] = curPayment;
appendPaymentTable(curPayment);
updateServerTable();
updateSummary();
billAmtInput.value = '';
tipAmtInput.value = '';
}
}
// createCurPayment() will return undefined with negative or empty inputs
// positive billAmt is required but tip can be 0
function createCurPayment() {
let billAmt = billAmtInput.value;
let tipAmt = tipAmtInput.value;
if (billAmt === '' || tipAmt === '') return;
if (Number(billAmt) > 0 && Number(tipAmt) >= 0) {
return {
billAmt: billAmt,
tipAmt: tipAmt,
tipPercent: calculateTipPercent(billAmt, tipAmt),
}
}
}
// Create table row element and pass to appendTd with input value
function appendPaymentTable(curPayment) {
let newTr = document.createElement('tr');
newTr.id = 'payment' + paymentId;
appendTd(newTr, '$' + curPayment.billAmt);
appendTd(newTr, '$' + curPayment.tipAmt);
appendTd(newTr, '%' + curPayment.tipPercent);
appendDeleteBtn(newTr, 'payment');
paymentTbody.append(newTr);
}
// Create table row element and pass to appendTd with calculated sum of all payment
function updateSummary() {
let tipPercentAvg = sumPaymentTotal('tipPercent') / Object.keys(allPayments).length;
summaryTds[0].innerHTML = '$' + sumPaymentTotal('billAmt');
summaryTds[1].innerHTML = '$' + sumPaymentTotal('tipAmt');
summaryTds[2].innerHTML = Math.round(tipPercentAvg) + '%';
}