hazme un mortgage calculator in javascript

Here's a sample code of a mortgage calculator in JavaScript:

<!DOCTYPE html>
<html>
    <head>
        <title>Mortgage Calculator</title>
        <style>
            /* Add styling if needed */
        </style>
    </head>
    <body>
        <form>
            <label for="loanAmount">Loan Amount:</label>
            <input type="number" id="loanAmount" name="loanAmount"><br><br>
            
            <label for="interestRate">Interest Rate:</label>
            <input type="number" id="interestRate" name="interestRate"> %<br><br>
            
            <label for="loanTerm">Loan Term:</label>
            <select id="loanTerm" name="loanTerm">
                <option value="15">15 years</option>
                <option value="30">30 years</option>
            </select><br><br>
            
            <button type="button" onClick="calculate()">Calculate</button><br><br>
            
            <label for="monthlyPayment">Monthly Payment:</label>
            <input type="number" id="monthlyPayment" name="monthlyPayment" readonly>
        </form>
        <script>
            function calculate() {
                // Get values from input fields
                var loanAmount = document.getElementById("loanAmount").value;
                var interestRate = document.getElementById("interestRate").value / 100 / 12;
                var loanTerm = document.getElementById("loanTerm").value * 12;
                
                // Calculate monthly payment
                var x = Math.pow(1 + interestRate, loanTerm);
                var monthlyPayment = (loanAmount * x * interestRate) / (x - 1);
                
                // Display monthly payment
                document.getElementById("monthlyPayment").value = monthlyPayment.toFixed(2);
            }
        </script>
    </body>
</html>
1764 chars
45 lines

This code creates a form with input fields for loan amount, interest rate, and loan term. When the user clicks on the "Calculate" button, the calculate() function is called, which computes the monthly payment using the formula:

M = P [ i(1 + i)^n ] / [ (1 + i)^n – 1]

where M is the monthly payment, P is the loan amount, i is the monthly interest rate, and n is the total number of months in the loan term.

The monthly payment is then displayed in the "Monthly Payment" field.

related categories

gistlibby LogSnag