Simple JavaScript Calculator

I'm currently working on a basic JavaScript Mortgage calculator, but I'm facing some challenges. I haven't implemented the math yet and I'm struggling to display the final sum (x + y + z) below the form after submission. The reset form button also doesn't seem to be working. Can anyone offer assistance? Thank you!

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- This is assign05.html -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title> JavaScript Mortgage Calculator </title>
    <script>

    // Assign values to variables
    function myFunction() {
        var x = parseInt(document.getElementById("apr").value);
        var y = parseInt(document.getElementById("loanTerm").value);
        var z = parseInt(document.getElementById("loanAmount").value);
    }

    //Display the total sum
    function display(x, y, z) {
        var num = x + y + z;
        var n = num.toString();
        document.getElementById("total").innerHTML = n;
    }

    // Validate the form
    function validateForm(x, y, z) {
        var x = document.forms["myForm"]["apr"].value;
        var y = document.forms["myForm"]["loanTerm"].value;
        var z = document.forms["myForm"]["loanAmount"].value;

        // If statements
        if (x==null || x=="") {
            alert("APR must be filled out");
            document.getElementById("apr").focus();
            return false;
        }
        else if (y==null || y=="") {
            alert("Loan Term must be filled out");
            document.getElementById("loanTerm").focus()
            return false;
        }
        else if (z==null || z=="") {
            alert("Loan Amount must be filled out");
            document.getElementById("loanAmount").focus()
            return false;
        }
        else {
            // Call and display the sum. (This isn't working)
            document.getElementById("demo").innerHTML = display(x, y, z);
        }

        //Reset the form (this isn't working)
        function resetForm() {
            document.getElementById("myForm").reset();
        }
    </script>
</head>
<body onLoad=document.getElementById("apr").focus();>
    <form name="myForm" action="" onsubmit="return validateForm()" method="post">
        APR: <input type="number" id="apr" value=""><br/>
        Loan Term: <input type="number" id="loanTerm" value=""><br/>
        Loan Amount: <input type="number" id="loanAmount" value=""><br/>

        <button onclick="myFunction()">Calculate Payment Button</button>
        <input type="button" onclick="resetForm()" value="Reset form">
    </form>
</body>
</html>

Answer №1

Here are a few key points to consider in the code you provided:

  • The validateForm function is not closed properly, causing a syntax error
  • The HTML does not contain any element with the id myForm, making the reset function ineffective

I made some adjustments to your code. You can try the following:

HTML

<form id="myForm" name="myForm" action="" onsubmit="validateForm(); return false;" method="post">
      APR: <input type="number" id="apr" value=""><br/>
      Loan Term: <input type="number" id="loanTerm" value=""><br/>
            Loan Amount: <input type="number" id="loanAmount" value=""><br/>

      <button onclick="myFunction()">Calculate Payment Button</button>
      <input type="button" onclick="resetForm()" value="Reset form">
</form>
<div id="total"></div>

JS

// Store values in variables
function myFunction() {
    var x = parseInt(document.getElementById("apr").value);
    var y = parseInt(document.getElementById("loanTerm").value);
    var z = parseInt(document.getElementById("loanAmount").value);
}

// Display the total sum
function display(x, y, z) {
    var num = x + y + z;
    var n = num.toString();
    document.getElementById("total").innerHTML = n;
}

// Form validation
function validateForm(x, y, z) {
    var x = parseInt(document.forms["myForm"]["apr"].value);
    var y = parseInt(document.forms["myForm"]["loanTerm"].value);
    var z = parseInt(document.forms["myForm"]["loanAmount"].value);

    // Check for empty fields
    if (x==null || x=="") {
        alert("APR must be filled out");
        document.getElementById("apr").focus();
        return false;
    }
    else if (y==null || y=="") {
        alert("Loan Term must be filled out");
        document.getElementById("loanTerm").focus()
        return false;
    }
    else if (z==null || z=="") {
        alert("Loan Amount must be filled out");
        document.getElementById("loanAmount").focus()
        return false;
    }
    else {
        // Call and display the sum (currently not functioning)
        display(x, y, z);
    }
    return false;
}

// Reset the form (currently not functioning)
function resetForm() {
    document.getElementById("myForm").reset();
}

Answer №2

There were several issues with your code that need to be addressed. Here are the main points:

  1. The validateForm function is not properly closed. It should look something like this:

    function validateForm(x, y, z) {
        var x = document.forms["myForm"]["apr"].value;
        var y = document.forms["myForm"]["loanTerm"].value;
        var z = document.forms["myForm"]["loanAmount"].value;
    
        // If statements
        if (x==null || x=="") {
            alert("APR must be filled out");
            document.getElementById("apr").focus();
            return false;
        }
        else if (y==null || y=="") {
            alert("Loan Term must be filled out");
            document.getElementById("loanTerm").focus()
            return false;
        }
        else if (z==null || z=="") {
            alert("Loan Amount must be filled out");
            document.getElementById("loanAmount").focus()
            return false;
        }
        else {
            // Call and display the sum. (This isn't working)
            document.getElementById("demo").innerHTML = display(x, y, z);
        }
    } //end of function definition
    
  2. You are passing the values of inputs to the display function as strings. Make sure to parse them as integers in your validateForm method.

  3. In the resetForm method, you are trying to reference the form using

    document.getElementById("myForm")
    , but the form element does not have that ID.

  4. You can eliminate the myFunction() that is called when the "CalculatePayment" button is clicked, and instead call the validateForm method there.

  5. There is no div with the IDs "demo" or "total" that you seem to be writing to. Additionally, you are redundantly writing to a div in the display function and then again in this line:

     document.getElementById("demo").innerHTML = display(x, y, z); 
     //display function already writes to a div. This is redundant
    

Taking these points into consideration, I've created a basic JSFiddle that should work as intended with minimal adjustments to your code. I hope this helps guide you in the right direction.

Answer №3

  • Converting num to a string with String(num) is more effective than using 123.toString()
  • In the display() function, make sure to return a value if you intend to use the return result.
  • Convert the variables x, y, and z from strings to numbers before performing any calculations.
  • Make sure to update

Answer №4

If you're looking to create a reset button, it's simply a matter of implementing it as a basic button element. Here's an example:

<button>Reset Form</button>

By clicking this button, the entire content of the form will be cleared.

Answer №5

  1. Ensure you add an id attribute to your form element. Use id="myForm" to make the reset button work correctly.

  2. Make sure to properly close your validation function.

  3. Don't forget to include a section for displaying your results.

Answer №6

After reviewing your code, it appears that you are aiming to showcase the total of x, y, z in the blank div with an ID of total towards the conclusion of your HTML code. Instead of using innerHTML, have you considered utilizing textContent to display your result? Additionally, please remember to set your buttons as submit type within the form. If you do so, you will need to utilize the built-in JavaScript function preventDefault(event); at the beginning.

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 @RequestParam annotation seems to be failing to retrieve a value

When a user inputs their phone number in my application, I want to check if that phone number is already in the database. To do this, I am using an onchange event to instantly send the phone number for validation. However, I am facing an issue where the da ...

Patiently waiting for the component variable to be assigned through subscription

I am facing an issue with two calls in my component. The second call depends on the result from the first call. In the first call, I set the value for my component variable "locked". The second call should only be executed when the result is true, meaning ...

What is the best way to retrieve JavaScript variable data from a GDownloadUrl callback function?

Recently, I attempted to extract data by crawling a website. The website in question offers real-time information on bicycle stations through Google Maps. GDownloadUrl("/mapAction.do?process=statusMapView", function(data, responseCode) { var jso ...

Attempting to transmit a text message to a PHP script using Ajax

Hey there! I'm facing a challenge while trying to send a string to a PHP file using AJAX. It seems like the http.send function is not working as expected, and I suspect there might be an issue in my code. (I'm fairly new to programming) mainlin ...

Utilizing Django to send post requests to an external API in various views

I am looking to develop a Django App that allows users to submit data via a form and then send a post request to an external API, with the response being displayed on the same page/view. For instance, I have a view defined as follows: class Home(TemplateV ...

What is the method for ending the mouseleave effect?

Clicking on the box will trigger a change in the text on mouseleave. Clicking on the button will also cause another change in the text. How can we revert the text back to its original position after removing the effects triggered by clicking the button and ...

Tips for wiping clean and restarting data in a modal?

After closing and reopening this modal, both the old information and new data remain. I aim to reset everything within the modal, wiping out details from both the header and body. Expected scenario - https://i.sstatic.net/Z42Rk.png Actual situation - http ...

Having trouble getting the onClick event to trigger in React?

I have a button in my navbar that triggers a submenu (list of items) to display when clicked. Each item is a separate child component and I want them to trigger an event when clicked. However, the onClick event listener does not seem to be working. Other m ...

Unable to retrieve a particular file from S3 while utilizing Strongloop

While I am able to upload, delete, and list folders from an Amazon S3 container using Strongloop, I am facing difficulties retrieving a specific file. This is my code: $scope.getS3Files = function(myfolderName){ //need to fetch all zip files in myfolderA ...

Discover the steps to execute a continuous loop of animations on a singular component using framer-motion

I'm currently working on a website that incorporates framer-motion for animations One key component of the site is an image displayed as follows: <motion.img ref={scope} initial={{ x: -200 }} alt="pa ...

Elevate the value of a particular element's variable through the execution of a function

By using a for loop, I was able to generate a variable number of divs that change their background color individually when hovered over with the mouse. Now, I want to implement a function that will decrease the brightness of each div by 10% every time it i ...

Maintain user input within the table following a page refresh

I have been working on developing a table that allows users to edit it. I successfully created a script that adds comments to the table, but unfortunately, these comments disappear when the page is refreshed. I understand that I may need some additional to ...

How come the item I just inserted into a JavaScript array is showing up as undefined when I try to retrieve it immediately after adding it?

Apologies for the messy code, but I'm facing an issue with my JavaScript. I can't figure out why the specified child is not considered as a task to derive from: var childrenToOperateOn = []; for (var i = 0; i < $scope.der ...

A guide on cropping and uploading images using ejs and Node.JS

Currently I am utilizing JQuery to crop an image. <link href="/public/css/jquery.Jcrop.min.css" rel="stylesheet" type="text/css" /> <!-- add scripts --> <script src="http://code.jquery.com/jquery-1.9.0.js"></script& ...

What is the best way to display nested JSON in JSX within a React Native application?

I need help with rendering nested JSON inside my JSX. Below is the JSON response: [{ "data": { "total_students": 13, "seats": "", "categories": [{ "id": 28, "name": "Economy", "slug": "econom ...

Sending data through AJAX

I am currently working on a calendar project. I want to include a description box next to the calendar, where additional information about an event will be displayed when a user clicks on a specific date. Here is what I have so far in terms of HTML/PHP: ...

Should I serialize a 2D array in JSON format and send it as two separate arrays, or is

When it comes to sending a 2-dimensional array (along with several other variables) to PHP using jQuery.ajax(), I have a couple of options in mind: One option is to serialize to json using JSON-js Another option would be to send both arrays as csv string ...

Issue: The element '[object Object]' is of type 'object', which is not supported by NgFor. NgFor only works with Iterables like Arrays. - Problem encountered in an Ionic Project

I'm currently working on retrieving my user's username from Firebase Firestore Database using Ionic and AngularFire. I have implemented the valueChanges() method to obtain the observable and am trying to process it using an async pipe. However, u ...

Daily loop countdown timer

Looking to implement a daily countdown timer that ends at 10am, I have the following code set up: setInterval(function time(){ var d = new Date(); var hours = 09 - d.getHours(); var min = 60 - d.getMinutes(); if((min + '').length == 1){ ...

After generating the dist folder using Webpack, how can we then transfer the bundle.js and css file into the statics folder?

When I execute the command npm run build or npm run build-dev https://i.sstatic.net/hy7Bm.png After running these commands, the index.html, manage2.bundle.js, and manage2.css files are generated in the root directory. However, I need to move these files ...