JAVASCRIPT   31
calculate
Guest on 11th March 2023 12:14:38 AM


  1. function calculate() {
  2.     //Look up the input and output elements in the document
  3.     var amount = document.getElementById("amount");
  4.     var apr = document.getElementById("apr");
  5.     var years = document.getElementById("years");
  6.     var payment = document.getElementById("payment");
  7.     var total = document.getElementById("total");
  8.     var totalinterest = document.getElementById("totalinterest");
  9.  
  10.     // Get the user's input from the input elements.
  11.     // Convert interest from a percentage to a decimal, and convert from
  12.     // an annual rate to a monthly rate. Convert payment period in years
  13.     // to the number of monthly payments.
  14.     var principal = parseFloat(amount.value);
  15.     var interest = parseFloat(apr.value) / 100 / 12;
  16.     var payments = parseFloat(years.value) * 12;
  17.  
  18.     // compute the monthly payment figure
  19.     var x = Math.pow(1 + interest, payments); //Math.pow computes powers
  20.     var monthly = (principal * x * interest) / (x - 1);
  21.  
  22.     // If the result is a finite number, the user's input was good and
  23.     // we have meaningful results to display
  24.     if (isFinite(monthly)) {
  25.         // Fill in the output fields, rounding to 2 decimal places
  26.         payment.innerHTML = monthly.toFixed(2);
  27.         total.innerHTML = (monthly * payments).toFixed(2);
  28.         totalinterest.innerHTML = ((monthly * payments) - principal).toFixed(2);
  29.  
  30.         // Save the user's input so we can restore it the next time they visit
  31.         save(amount.value, apr.value, years.value, zipcode.value);
  32.  
  33.         // Advertise: find and display local lenders, but ignore network errors
  34.         try { // Catch any errors that occur within these curly braces
  35.             getLenders(amount.value, apr.value, years.value, zipcode.value);
  36.         } catch (e) { /* And ignore those errors */ }
  37.  
  38.         // Save the user's input as properties of the localStorage object. Those
  39.         // properties will still be there when the user visits in the future
  40.         // This storage feature will not work in some browsers (Firefox, e.g.) if you
  41.         // run the example from a local file:// URL. It does work over HTTP, however.
  42.         function save(amount, apr, years, zipcode) {
  43.             if (window.localStorage) { // Only do this if the browser supports it
  44.                 localStorage.loan_amount = amount;
  45.                 localStorage.loan_apr = apr;
  46.                 localStorage.loan_years = years;
  47.             }
  48.         }
  49.         // Automatically attempt to restore input fields when the document first loads.
  50.         window.onload = function() {
  51.             // If the browser supports localStorage and we have some stored data
  52.             if (window.localStorage && localStorage.loan_amount) {
  53.                 document.getElementById("amount").value = localStorage.loan_amount;
  54.                 document.getElementById("apr").value = localStorage.loan_apr;
  55.                 document.getElementById("years").value = localStorage.loan_years;
  56.             }
  57.         };
  58.         // Pass the user's input to a server-side script which can (in theory) return
  59.         // a list of links to local lenders interested in making loans. This example
  60.         // does not actually include a working implementation of such a lender-finding
  61.         // service. But if the service existed, this function would work with it.
  62.         function getLenders(amount, apr, years) {
  63.             // If the browser does not support the XMLHttpRequest object, do nothing
  64.             if (!window.XMLHttpRequest) return;
  65.             // Find the element to display the list of lenders in
  66.             var ad = document.getElementById("lenders");
  67.             if (!ad) return; // Quit if no spot for output
  68.  
  69.             // Encode the user's input as query parameters in a URL
  70.             var url = "getLenders.php" + // Service url plus
  71.                 "?amt=" + encodeURIComponent(amount) + // user data in query string
  72.                 "&apr=" + encodeURIComponent(apr) +
  73.                 "&yrs=" + encodeURIComponent(years);
  74.             // Fetch the contents of that URL using the XMLHttpRequest object
  75.             var req = new XMLHttpRequest(); // Begin a new request
  76.             req.open("GET", url); // An HTTP GET request for the url
  77.             req.send(null); // Send the request with no body
  78.             // Before returning, register an event handler function that will be called
  79.             // at some later time when the HTTP server's response arrives. This kind of
  80.             // asynchronous programming is very common in client-side JavaScript.
  81.             req.onreadystatechange = function() {
  82.                 if (req.readyState == 4 && req.status == 200) {
  83.                     // If we get here, we got a complete valid HTTP response
  84.                     var response = req.responseText; // HTTP response as a string
  85.                     var lenders = JSON.parse(response); // Parse it to a JS array
  86.                     // Convert the array of lender objects to a string of HTML
  87.                     var list = "";
  88.                     for (var i = 0; i < lenders.length; i++) {
  89.                         list += "<li><a href='" + lenders[i].url + "'>" +
  90.                             lenders[i].name + "</a>";
  91.                     }
  92.                     // Display the HTML in the element from above.
  93.                     ad.innerHTML = "<ul>" + list + "</ul>";
  94.                 }
  95.             }
  96.         }
  97.     }
  98. }

Raw Paste

Login or Register to edit or fork this paste. It's free.