What are the best ways to incorporate mistakes into my JavaScript mortgage calculator?

I am struggling to set up my calculator so that it triggers an error message if the APR goes over 25% or falls below 0. Also, the Loan Term should be greater than 0 and less than or equal to 40, otherwise display an error message. I have attempted different approaches but haven't been able to solve it.

APR (Annual Percentage Rate)—this is a text input field. Assign the name and id of apr. It should only accept floating point values between 0 and 25.00%. Loan Term (in years)—another text input field with the name and id term. The value must be greater than zero and less than or equal to 40. Loan Amount (in dollars)—a text input field with the name and id amount.

   <div>
<form action="">
<label> APR%: </label><br>
  <label><input type="number" id="apr" name="APR" placeholder ="Enter Annual Percentage Rate...."/></label><br>
  <label> Loan Term: </label><br>
  <label>  <input type="number" id="term" name="Term"placeholder ="Enter Loan Term...."/></label><br>
  <label> Loan Amount: </label><br>
  <label> <input type="number" id="amount" name="Amount" placeholder ="Enter Loan Amount...."/></label><br>
  <label> Monthly Payment: </label><br>
  <input type="text" id="payment" name="mPmt" placeholder ="Display Monthly Payment"/><br>
  <input type="button" onclick = "errors()" id="sbt" value="Submit" />
  <input type="reset" id="rst" value="Reset Form" />
</form>
</div>

<script>
var term;
var apr;
var amount;
var mPmt;


window.onload = function()
{
  document.getElementById("apr").focus();
  document.getElementById("sbt").onclick = getValues;
};

//use toFixed(2) to set the precision of the mPayment. Use it on an int.
function getValues()
{
  term = document.getElementById("term").value;
  apr = document.getElementById("apr").value;
  amount = document.getElementById("amount").value;
  apr /=1200;
  term *= 12;
  mPmt = calculatePayment();
  document.getElementById("payment").value = "$" + mPmt.toFixed(2);
};
function calculatePayment()
{
    var payment = amount*(apr * Math.pow((1 + apr), term))/(Math.pow((1 + apr), term) - 1);
    return payment;``
    }
function errors() {
var message , x;
message = document.getElementById("01");
message.innerHTML ="";
x = document.getElementById("apr").value;
try{
if (x == "") throw "empty";
if (isNaN(apr)) throw "not a number";
x = Number(x);
if (apr < 0) throw "should be a postive integer";
if (apr > 25) throw "apr can only be up to 25.00% but not less than 0";
}

catch(err) {
message.innerHTML = "Input is " + err
}

}

</script>

Answer №1

There appear to be some issues in the code you provided:

  1. The element responsible for displaying messages was not found
  2. The error checking function was never invoked

var term;
var apr;
var amount;
var mPmt;

window.onload = function() {
  document.getElementById("apr").focus();
  // attaching event listener to form submission:
  document.getElementById("form").addEventListener("submit", submitForm)
};

function getValues() {
  term = document.getElementById("term").value;
  apr = document.getElementById("apr").value;
  amount = document.getElementById("amount").value;
  apr /= 1200;
  term *= 12;
  mPmt = calculatePayment();
  document.getElementById("payment").value = "$" + mPmt.toFixed(2);
};

function calculatePayment() {
  var payment = amount * (apr * Math.pow((1 + apr), term)) / (Math.pow((1 + apr), term) - 1);
  return payment;
}

function submitForm(e) {
  e.preventDefault()
  getValues()
  errors()
}

function errors() {
  var message, x;
  message = document.getElementById("01");
  message.innerHTML = "";
  x = document.getElementById("apr").value;
  try {
    if (x == "") throw "empty";
    if (isNaN(apr)) throw "not a number";
    x = Number(x);
    if (apr < 0) throw "should be a postive integer";
    if (apr > 25) throw "apr can only be up to 25.00% but not less than 0";
  } catch (err) {
    message.innerHTML = "Input is " + err
  }

}
<div>
  <form id="form">
    <label> APR%: </label><br>
    <label><input type="number" id="apr" name="APR" placeholder ="Annual Percentage Rate...."/></label><br>
    <label> Loan Term: </label><br>
    <label>  <input type="number" id="term" name="APR"placeholder ="Loan Term...."/></label><br>
    <label> Loan Amount: </label><br>
    <label> <input type="number" id="amount" name="amount" placeholder ="Loan Amount...."/></label><br>
    <label> Monthly Payment: </label><br>
    <input type="text" id="payment" name="mPmt" placeholder="Display Monthly Payment" /><br>
    <input type="submit" id="sbt" value="Submit" />
    <input type="reset" id="rst" value="Reset Form" />
  </form>
  <div id="01"></div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The behavior of the select menu is erratic when interacting with AJAX

My dropdown menu is populated dynamically based on AJAX response: function populateDropdown(dropdownNum) { // invokeWebService using $.ajax json = invokeWebService("GET", "/webservice/dropwdownOptions"); optionsHtml = ""; $.each(json, function(count, jsO ...

I tried utilizing the wrapper feature, but unfortunately, the modal did

import React, { PropTypes } from 'react'; import Dialog from 'material-ui/Dialog'; export default class CustomModal extends React.Component { constructor(props){ super(props) } handlePrimaryButton = () => { this.prop ...

Achieving Vertical Content Alignment in Bootstrap 4

I am struggling to achieve a responsive design where two columns stack vertically on top of each other when viewed on smaller mobile screens. Despite numerous attempts, I have been unable to figure it out. Ideally, I want the layout to look like this imag ...

How should elements be properly inserted into injected HTML code?

We are currently phasing out our custom forms in React on the website, and transitioning to Microsoft Dynamics 365 generated forms. These new forms are injected through a React placeholder component created by a script that loads the js bundle and inserts ...

Guide on uploading a file to Pinata directly from a React application

I keep encountering the 'MODULE_NOT_FOUND' console error code. Displayed below is the complete console error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f4b4d564b5a4d4d5e4c1251505b5a7f0e110f110f">[email& ...

Navigating with Vue.js using programmatic methods while passing props

I am working with a Vue component that includes a prop called 'title' like this: <script> export default { props: ['title'], data() { return { } } } </script> After completing a specific action, I need to pro ...

Having difficulty incorporating external SASS styles into my React.js project

In most of my projects, I follow a similar process for importing SASS styles. First, I create my react app and then install SASS using the command npm install node-sass. Next, I import my SASS file into my app components as shown below: import React from & ...

An issue arose during the page prerendering process for "/" on Vercel | Next.js resulting in a deployment error

When attempting to deploy my website using Vercel and generating static pages, I encountered the following error in the logs: info - Generating static pages (0/6) Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/ ...

Is it possible to include a visible comment in an ajax call that can be viewed in Fiddler when analyzing the outgoing data?

Here is an example of the code I am working with: $.ajax({ cache: false, url: "/xx" }).done(onAjaxDone).fail(function (jqXHR, textStatus, errorThrown) { Dialog.Alerts.ajaxOnFailure(jqXHR, textStatus, err ...

Organizing the directory layout for the /profile/username/followers route in NextJs

I want to set up a folder structure for my website that can accommodate the URL /profile/username/followers, where the username will be different for each user. The proposed folder structure is as follows: pages -- profile -- [username].js Curren ...

Tips on preventing the constant shifting of my webpage div elements when resizing the browser

Whenever I resize my webpage browser, the 3 text input boxes move and overlap, causing the page layout to become messy. View of The Browser in full screen (normal) View of The Browser when it's smaller (not normal) As a beginner programmer, I have ...

My attempt at utilizing the regex function was unsuccessful

When attempting to use a regex function for matching tags in the title and caption, it appears to work fine. However, adding more matching tags causes the function to fail. Below is the code snippet that functions correctly without any issues: $(".si ...

What are alternative methods for passing data to a template besides EJS?

app.get("/movies", function(req, res) { Movies.find({}, function (err, foundMovie){ if(err) { console.log(err); } else { res.render("movies/index", {movie_index:foundMovie}); } } }); I have written code to retrieve a movie and ...

Unable to render Angular charts

Recently, I've been attempting to integrate angular charts using the chart.js bundle sourced from CDN links. The version of Angular being used is 1.5.7 and for chart.js it's 2.1.6. I encountered the following error message: angular.js:13708 T ...

Create a visually appealing DataGrid cell by incorporating a vibrant colored oval with text or an icon inside

I'm in need of assistance with the mui/x-data-grid plugin. My goal is to display a cell within the grid containing both text and an icon, based on the value of the text. Unfortunately, I have been unable to achieve this so far. Here is the link to the ...

What's preventing me from drawing a line on this D3.js chart with my Angular code?

I am attempting to create a graph on my webpage using the D3.js library for JavaScript. I am able to draw a line on an SVG using HTML, but when I try to draw a line using JavaScript, I encounter the error message: ReferenceError: d3 is not defined. Even t ...

Efficiently loading Google Visualizations for core charts by utilizing AJAX within jQueryUI tabs

Loading Google Visualizations via AJAX in jQueryUI tabs After encountering a similar issue, I discovered a solution provided in the link above that partially resolved my problem. I am trying to use Google Visualization core charts within jQueryUI tabs wit ...

Can you tell me where the templates store their icons?

Hey there, thank you for taking the time to read my question. I have a template that can be found at this link: In the top left corner of the template, there is an icon of a home. I have copied the entire website, including images, css, and js files, but ...

How does the use of let versus const differ when iterating through a collection?

Utilizing Node.js (ES6) to iterate through each item in a collection like the one provided below: var statuses = [{ statusId: 1, description: 'New' }, { statusId: 2, description: 'Pending' }, { ...

Suggestions for deleting browser cache programmatically by utilizing JS or HTML

Having trouble clearing the Chrome browser cache using Add-ons. Working on a site development project using JSP with Java, it's crucial for security reasons to clear the cache. Tried multiple methods but none have been successful. Any suggestions? Ple ...