Build a Mortgage Calculator

A calculator is a good first project once you know the basics: it's a form, some JavaScript, and a result to display. Here's a small one, start to finish, built with nothing but plain HTML and JavaScript.

The HTML: a form and a result area

Three inputs, a submit button, and an empty paragraph to hold the answer:

<form id="calc">
  <label>Loan amount ($)
    <input type="number" id="amount" value="300000">
  </label>
  <label>Interest rate (% per year)
    <input type="number" id="rate" value="6.5" step="0.1">
  </label>
  <label>Term (years)
    <input type="number" id="years" value="30">
  </label>
  <button type="submit">Calculate</button>
</form>
<p id="result"></p>

The formula

A fixed-rate mortgage's monthly payment comes from one standard formula:

M = P * (r * (1 + r)^n) / ((1 + r)^n - 1)

Where P is the loan amount, r is the monthly interest rate (the annual rate divided by 12 and converted from a percentage), and n is the total number of monthly payments (years times 12).

The JavaScript

document.querySelector('#calc').addEventListener('submit', function (e) {
  e.preventDefault();

  const P = Number(document.querySelector('#amount').value);
  const r = Number(document.querySelector('#rate').value) / 100 / 12;
  const n = Number(document.querySelector('#years').value) * 12;

  const M = P * (r * Math.pow(1 + r, n)) / (Math.pow(1 + r, n) - 1);

  document.querySelector('#result').textContent =
    'Monthly payment: $' + M.toFixed(2);
});

e.preventDefault() stops the form from actually submitting and reloading the page. The three Number(...) lines read the form's current values and convert the rate into a monthly decimal and the term into a total payment count, matching what the formula expects. Math.pow(base, exponent) handles the ^ in the formula, since JavaScript doesn't have a built-in exponent operator in an expression like this. The result is written into the empty paragraph with textContent, rounded to two decimal places with toFixed(2).

Try it, then see it done

Save both pieces, link the script from your HTML the way the JavaScript basics guide covers, and open the page. Changing any input and clicking Calculate should update the result immediately.

Calcugator has a fuller version of this same idea already built, with input validation and formatting added on top of the same core formula.

← back to guides