-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
99 lines (78 loc) · 2.97 KB
/
index.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
88
89
90
91
92
93
94
95
96
97
98
99
const taxCalculatorForm = document.getElementById("tax-calculator-form")
const afterTaxesElem = document.getElementById("afterTaxes")
const dialog = document.querySelector("dialog")
const closeDialog = document.getElementById("close-dialog")
let afterTaxes
taxCalculatorForm.addEventListener("submit", (e) => {
e.preventDefault() //stop event propagation.
const invalidFields = validateForm()
if (invalidFields.length) {
notifyError(invalidFields)
} else {
const dialogTitle = document.getElementById("dialog-title")
const dialogFollowTitle = document.getElementById("dialog-follow-title")
const calculatedIncome = calcIncomeAfterTaxes()
if (isNaN(calculatedIncome)) {
dialogTitle.className = "hide-dialog-title"
dialogFollowTitle.className = "hide-dialog-follow-title"
} else {
dialogTitle.className = "show-dialog-title"
dialogFollowTitle.className = "show-dialog-follow-title"
}
afterTaxesElem.innerText = calculatedIncome
dialog.showModal()
}
})
closeDialog.addEventListener("click", (e) => {
e.preventDefault()
dialog.close()
})
function calcIncomeAfterTaxes() {
const formdata = new FormData(taxCalculatorForm)
const ageGrp = formdata.get("ageGrp")
let isTaxable = false
let taxPercentage
try {
const GAI = parseFloat(formdata.get("grossAnnualIncome"))
const EI = parseFloat(formdata.get("extraIncome"))
const Deduc = parseFloat(formdata.get("totalApplicableDeduc"))
const OI = GAI + EI - Deduc
if (OI > 8e5) {
isTaxable = true
}
if (isTaxable) {
switch (ageGrp) {
case "<40":
taxPercentage = 30 / 100
break;
case ">= 40 and <60":
taxPercentage = 40 / 100
break;
case ">=60":
taxPercentage = 10 / 100
break;
}
}
const totalTax = taxPercentage * (OI - 8e5)
afterTaxes = OI - totalTax
if (isNaN(afterTaxes)) {
afterTaxes = "Your Income is not taxable."
}
return afterTaxes
} catch (error) {
console.log(error)
}
}
// this func returns a array of invalid fields.
function validateForm() {
const formdata = new FormData(taxCalculatorForm)
Array.from(formdata.keys()).map((fieldname) => fieldname !== "ageGrp" && (document.getElementById(fieldname).nextElementSibling.style.visibility = "hidden"))
return Array.from(formdata.keys()).filter((fieldname) => fieldname !== "ageGrp" && (!formdata.get(fieldname) || isNaN(Number(formdata.get(fieldname)))))
}
// this function highlight the invalid fields.
function notifyError(fields) {
fields.forEach((field) => {
field = document.getElementById(field).nextElementSibling
field.style.visibility = "visible"
})
}