-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
87 lines (75 loc) · 2.36 KB
/
script.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"use strict";
let bill = document.getElementById("bill");
let currentTip = document.querySelector("input[type=radio]:checked");
let tips = document.getElementsByName("tip");
let custom = document.getElementById("custom");
let customTipInput = document.getElementById("customTipInput");
let persons = document.getElementById("persons");
let tipAmount = document.getElementById("tip-amount");
let total = document.getElementById("total");
let reset = document.getElementById("reset");
function setResetEnabled() {
if(bill.value === "" && currentTip === null && persons.value === "") {
reset.disabled = true;
return;
}
reset.disabled = false;
}
function calculateTipAndTotal() {
setResetEnabled();
if(bill.value !== "" &&
(currentTip !== null && currentTip.value !== "") &&
(persons.value !== "" && parseInt(persons.value) > 0)) {
let tipAmountI = (bill.value*currentTip.value) / persons.value;
tipAmount.innerHTML = "$" + tipAmountI.toFixed(2);
total.innerHTML = "$" + ((bill.value / persons.value) + tipAmountI).toFixed(2);
return;
}
tipAmount.innerHTML = "$0.00";
total.innerHTML = "$0.00";
}
function validateDecimal(elem) {
let validNumber = new RegExp(/^\d+(\.\d+)?$/);
let lastValid = bill.value;
if (validNumber.test(elem.value)) {
lastValid = elem.value;
} else {
elem.value = lastValid;
}
}
bill.oninput = function() {
validateDecimal(this);
calculateTipAndTotal();
}
for (var i = 0; i < tips.length; i++) {
tips[i].addEventListener('change', function() {
if(this.checked) {
currentTip = this;
calculateTipAndTotal();
}
});
}
customTipInput.onfocus = function() {
custom.checked = true;
currentTip = custom;
calculateTipAndTotal();
}
customTipInput.oninput = function() {
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');
custom.value = this.value / 100;
calculateTipAndTotal();
}
persons.oninput = function() {
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');
calculateTipAndTotal();
}
reset.onclick = function() {
bill.value = "";
customTipInput.value = "";
if(currentTip !== null) {
currentTip.checked = false;
currentTip = null;
}
persons.value = "";
calculateTipAndTotal();
}