draw ‘til you’re soreWelcome to the bog of Jessica Amber. Herein you’ll find my life, whatever Irandom stuff ’m getting up to. It’s usually creative.
Unmaintained since 2019. Please go to www.jessicaamber.com.au This site contains affiliate links.
|
So I've been doing the TAFE unit ICTWEB411, regarding writing client-side scripts. The assignment for this unit was to create a Mortgage Calculator to their specifications. This included varying interest rates based on the principal, calculating based on different repayment periods (monthly, weekly, ect). Default values. Automatic updating. And it had to resemble a screenshot they provided. It was challenging, but I did it!
Below is my solution. It doesn't look like the example just because I don't know about attaching CSS code to an 'embed code' weebly element.
Next I'll show you the HTML5-compliant + JavaScript code I used to achieve this goal.
The way I approached this was, first I created the form. All the asides, sections, divs, are just for making the box look like it did in the example photo. Then I created variables for the three inputs of 'Number of Years' (y), 'Loan Amount' (p, as in principal), and 'Payment Frequency' (t, as in time). Variable called repayments will hold what the repayment amount is. Variable tText is an array to hold the words for the payment frequencies that appears after the repayment amount. The three input variables get immediately updated by the updater() function, which you can see in the <body> tag of the HTML, gets invoked as soon as the page loads. Then in the updater(), a conditional branch runs based on what Payment Frequency you have selected. Say you picked Weekly. Then it will run the CalculateInterestWeekly() function. Please note that I am just a beginner in terms of JavaScript. I'm aware there is probably more efficient ways of writing this code, but it works for me and seems pretty simple to convey to others, so let's roll with it, shall we? The different interest rates are stored in an array called iR. The variable periodRate will hold whatever the relevant interest rate is, divided by 100 (to make it a percentage) and divided by the number of Payment Frequencies per year (so for weekly, we would divide by 52). A bunch of variables get declared for things like that 52 weeks in a year, 26 fortnights in a year, ect. We come to the CalculateInterestWeekly function. I declare variables top and bottom to hold each part of the repayment interest calculation equation. That's optional, of course, you could write it all in one line, but this made it easier for me to comprehend. A conditional branch runs based on what the principal is. For each possible range (under 200000, else if under 250000, ect) I assign a value to periodRate, using references to the interest rate array, so if principal is <200000, it calls the first array item, ir[0], which is 5.4% After those conditions are processed, then the variables top and bottom are used, being given the values of the two halves of the fraction that makes the calculation. (So top will be the r*p part, and bottom will be the 1 - (1 + r) ^ -n part)
r, the repayments variable, is given the value of top divided by bottom.
Then that r value is inserted into an input in the form. Wash, rinse, and repeat, making formulas for updates that are fortnightly, monthly, quarterly and yearly.
<!DOCTYPE html>
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Mortgage Calculator</title> <link href="style.css" rel="stylesheet" type="text/css"> </head> <body onload="updater()"><!--this makes the repayments info update right as the page opens--> <p> </p> <aside id="info-block"> <section class="padder"> <!--This following div keeps the Mortgage title interseting the border--> <div> <!--This following div holds the title--> <div class="box-title"> Mortgage Calculator </div> <div id="mortgageBox"> <form id="mortgageForm"> <p> <label for="numOfYears">Number of Years:</label> <input type="number" name="numOfYears" title="Please type in the time period of the loan in years" id="numOfYears" value="30" onchange="updater()"> </p> <p> <label for="loanAmount">Loan Amount:</label> <input type="number" name="loanAmount" id="loanAmount" title="Please type in the value of the loan" value="200000" onchange="updater()"> </p> <p> <label for="paymentFreq">Payment Frequency:</label> <select name="paymentFreq" id="paymentFreq" title="Please select how often you intend to make repayments" onchange="updater()"> <option value="weekly">Weekly</option> <option value="fortnightly">Fortnightly</option> <option value="monthly">Monthly</option> <option value="quarterly">Quarterly</option> <option value="yearly">Yearly</option> </select> </p> <div class="noborder"><!--this gets rid of the border around the following 2 inputs--> <p>The repayment amount is $<input type="text" name="repaymentField" id="repaymentField" readonly> each <input type = "text" name="freqLabel" id="freqLabel" value="week" readonly> </div> </form> </div> </div> </section> </aside> <script> <!--y=years, p=principal, t=time--> var y = Number(document.getElementById("numOfYears").value); var p = Number(document.getElementById("loanAmount").value); var t = document.getElementById("paymentFreq").value; var repayments; var tText = ["week", "fortnight", "month", "quarter", "year"]; function updater() { //first three variables get updated upon element being changed y = document.getElementById("numOfYears").value; p = Number(document.getElementById("loanAmount").value); t = document.getElementById("paymentFreq").value; //conditional branch that runs based on what the payment frequency is if (t == "weekly") { document.forms['mortgageForm'].freqLabel.value = tText[0]; //Changes the payment frequency in the results calculateInterestWeekly(); //runs the weekly interest function } else if (t == "fortnightly") { document.forms['mortgageForm'].freqLabel.value = tText[1]; calculateInterestFortnightly(); } else if (t == "monthly") { document.forms['mortgageForm'].freqLabel.value = tText[2]; calculateInterestMonthly(); } else if (t == "quarterly") { document.forms['mortgageForm'].freqLabel.value = tText[3]; calculateInterestQuarterly(); } else { document.forms['mortgageForm'].freqLabel.value = tText[4]; calculateInterestYearly(); } } // interest rates. 0 upto 200000, 1 upt 250, 2 upto 500, 3 upto 750, 4 over 750// var iR = ["5.4", "5.09", "4.84", "4.79", "4.5"] //many variables needed for the interest functions var periodRate = 0; //Will hold interest rate var weeksInYear = 52; var fortnightsInYear = 26; var monthsInYear = 12; var quartersInYear = 4; var weeksByYears = y * weeksInYear; var fortnightsByYears = y * fortnightsInYear; var monthsByYears = y * monthsInYear; var quartersByYears = y * quartersInYear; function calculateInterestWeekly() { var top; var bottom; //I tried having the vars top and bottom declared in the global before, it didn't work //Conditional branch based on what the principal is if (p < 200000) { periodRate = iR[0] / 100 / weeksInYear; //Turn rate into percentage, then divide by repayment periods in a year } else if (p <= 250000) { periodRate = iR[1] / 100 / weeksInYear; } else if (p <= 500000) { periodRate = iR[2] / 100 / weeksInYear; } else if (p <= 7500000) { periodRate = iR[3] / 100 / weeksInYear; } else { periodRate = iR[4] / 100 / weeksInYear; } //The mathematics to find the repayment amount, and fill those values into the form top = periodRate * p; bottom = 1 - (Math.pow((1 + periodRate), -weeksByYears)); r = (top / bottom).toFixed(2); document.forms['mortgageForm'].repaymentField.value = r; } function calculateInterestFortnightly() { var top; var bottom; if (p < 200000) { periodRate = iR[0] / 100 / fortnightsInYear; //Turn rate into percentage, then divide by repayment periods in a year } else if (p < 250000) { periodRate = iR[1] / 100 / fortnightsInYear; } else if (p < 500000) { periodRate = iR[2] / 100 / fortnightsInYear; } else if (p < 7500000) { periodRate = iR[3] / 100 / fortnightsInYear; } else { periodRate = iR[4] / 100 / fortnightsInYear; } top = periodRate * p; bottom = 1 - (Math.pow((1 + periodRate), -fortnightsByYears)); r = (top / bottom).toFixed(2); document.forms['mortgageForm'].repaymentField.value = r; } function calculateInterestMonthly() { var top; var bottom; if (p < 200000) { periodRate = iR[0] / 100 / monthsInYear; //Turn rate into percentage, then divide by repayment periods in a year } else if (p < 250000) { periodRate = iR[1] / 100 / monthsInYear; } else if (p < 500000) { periodRate = iR[2] / 100 / monthsInYear; } else if (p < 7500000) { periodRate = iR[3] / 100 / monthsInYear; } else { periodRate = iR[4] / 100 / monthsInYear; } top = periodRate * p; bottom = 1 - (Math.pow((1 + periodRate), -monthsByYears)); r = (top / bottom).toFixed(2); document.forms['mortgageForm'].repaymentField.value = r; } function calculateInterestQuarterly() { var top; var bottom; if (p < 200000) { periodRate = iR[0] / 100 / quartersInYear; //Turn rate into percentage, then divide by repayment periods in a year } else if (p < 250000) { periodRate = iR[1] / 100 / quartersInYear; } else if (p < 500000) { periodRate = iR[2] / 100 / quartersInYear; } else if (p < 7500000) { periodRate = iR[3] / 100 / quartersInYear; } else { periodRate = iR[4] / 100 / quartersInYear; } top = periodRate * p; bottom = 1 - (Math.pow((1 + periodRate), -quartersByYears)); r = (top / bottom).toFixed(2); document.forms['mortgageForm'].repaymentField.value = r; } function calculateInterestYearly() { var top; var bottom; if (p < 200000) { periodRate = iR[0] / 100; //Turn rate into percentage, then divide by repayment periods in a year } else if (p < 250000) { periodRate = iR[1] / 100; } else if (p < 500000) { periodRate = iR[2] / 100; } else if (p < 7500000) { periodRate = iR[3] / 100; } else { periodRate = iR[4] / 100; } top = periodRate * p; bottom = 1 - (Math.pow((1 + periodRate), -y)); r = (top / bottom).toFixed(2); document.forms['mortgageForm'].repaymentField.value = r; } </script> </body> </html>
This was quite a challenging assignment, but I'm glad that my perseverance paid off. And I hope that other students can be helped by viewing my code. Don't copy it verbatim, obviously. Not only would that look bad to assessors, but you want to gain the knowledge, and just blindly copy-pasting won't achieve that. Take the time to try and understand what each variable and function does.
I found that when doing this unit, the previous knowledge I'd gained when studying C# was very helpful. The structure and content of the two languages are similar in a lot of ways. I personally find JavaScript easier because it's so fluid to just declare variables without having to specify what they will contain. Something that annoyed me, though, was the distinct lack online of code validators that could analyse JavaScript and HTML within the same document simultaneously. It was always either one or the other. I would like to recommend the website https://www.danstools.com/javascript-beautify/ for validating your code. Lots of validation sites report errors if you have tabs instead of spaces, and this site will convert those tabs to spaces, saving you a lot of trouble. If there is anything you want to ask me about this code, I will do my best to answer. Until next time, Jess xx
0 Comments
Leave a Reply. |
AuthorI'm just some Aussie 20-something year old with a lot of time and a lot of interests. Archives
July 2019
CategoriesAll Art Art Freelancing Business Cosplay Food Law Of Attraction Makeup Organizing Sewing Shopping TAFE Technology Web |