-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.js
52 lines (38 loc) · 1.71 KB
/
calculator.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
document.getElementById('loan-form').addEventListener('submit', calculateResult);
function calculateResult(e) {
const amount = document.getElementById('amount');
const interest = document.getElementById('interest');
const years = document.getElementById('years');
const monthlyPayment = document.getElementById('monthly-payment');
const totalPayment = document.getElementById('total-payment');
const totalInterest = document.getElementById('total-interest');
const principal = parseFloat(amount.value);
const calculatedInterest = parseFloat(interest.value) / 100 / 12;
const calculatedPayments = parseFloat(years.value) * 12;
const x = Math.pow(1 + calculatedInterest, calculatedPayments);
const monthly = (principal * x * calculatedInterest) / (x - 1);
// to check if monthly value is finite
if (isFinite(monthly)) {
monthlyPayment.value = monthly.toFixed(2);
totalPayment.value = (monthly * calculatedPayments).toFixed(2);
totalInterest.value = ((monthly * calculatedInterest) - principal).toFixed(2);
} else {
showError('please check your numbers');
}
e.preventDefault();
}
// showError
function showError(error) {
const errorDiv = document.createElement('div');
const card = document.querySelector('.card');
const heading = document.querySelector('.heading ');
// to create className
errorDiv.className = 'alert alert-danger';
// to create textNode and append
errorDiv.appendChild(document.createTextNode(error));
card.insertBefore(errorDiv, heading)
setTimeout(clearError, 3000)
}
function clearError() {
document.querySelector('.alert').remove();
}