Created
November 4, 2020 05:43
-
-
Save whal-e3/88e215593bf8dc7b070ce560740959c8 to your computer and use it in GitHub Desktop.
JS Loan Calculator (isFinite(), setTimeout())
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Listen for submit | |
| document.getElementById('loan-form').addEventListener('submit', function (e) { | |
| // Hide results | |
| document.getElementById('results').style.display = 'none'; | |
| // Show loader | |
| document.getElementById('loading').style.display = 'block'; | |
| setTimeout(calculateResults, 2000); | |
| e.preventDefault(); | |
| }); | |
| // Calculate Results | |
| function calculateResults() { | |
| console.log('Calculating...'); | |
| // UI Vars | |
| 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); | |
| if (isFinite(monthly)) { | |
| monthlyPayment.value = monthly.toFixed(2); | |
| totalPayment.value = (monthly * calculatedPayments).toFixed(2); | |
| totalInterest.value = (monthly * calculatedPayments - principal).toFixed(2); | |
| // Show result | |
| document.getElementById('results').style.display = 'block'; | |
| // Hide loader | |
| document.getElementById('loading').style.display = 'none'; | |
| } else { | |
| showError('Please check your numbers'); | |
| } | |
| } | |
| function showError(error) { | |
| // Hide result | |
| document.getElementById('results').style.display = 'none'; | |
| // Hide loader | |
| document.getElementById('loading').style.display = 'none'; | |
| const card = document.querySelector('.card'); | |
| const heading = document.querySelector('.heading'); | |
| const errorDiv = document.createElement('div'); | |
| errorDiv.className = 'alert alert-danger'; | |
| errorDiv.appendChild(document.createTextNode(error)); | |
| card.insertBefore(errorDiv, heading); | |
| // Clear error after 3 sec | |
| setTimeout(clearError, 3000); | |
| } | |
| function clearError() { | |
| document.querySelector('.alert').remove(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment