What steps can I take to make sure my JavaScript code accurately calculates numbers without resulting in undefined or NaN values?

I'm having an issue with my javascript code for a simple interest calculator. Every time I try to calculate the amount, it keeps returning NaN. It seems like the code is treating the + as if I'm trying to concatenate strings, and I'm not sure how to fix that.

I've attempted to use parseInt and parseFloat, but the problem persists. Can someone please point out what I'm doing wrong?

Below is the code:

<!DOCTYPE html>
<html>
    <head>
    <script src="script.js"></script>
    <link rel="stylesheet" href="style.css">
    <title>Simple Interest Calculator</title>
</head>
    <body>
    <div class="container">
        <h1>Simple Interest Calculator</h1>
        
        <form id="form1">
        <label for="Amount"></label>
        Amount <input type="number"  id="principal">  
        <br/>
        <br/>
        <label for="Interest Rate"></label>
        <label for="Interest Rate">Interest Rate</label>
    <input onchange=updateValue(this) type="range" id="rate" min="1" max="20" step="0.25" default value="10.25">
    <span id="rate_val">10.25%</span>
        <br/>
        <br/>
        <label for="No. of Years"></label>
        No. of Years <select id="years">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
            <option value="7">7</option>
            <option value="8">8</option>
            <option value="9">9</option>
            <option value="10">10</option>
        </select> 
        <br/>
        <br/>
        
        <label for="Compute Interest"></label>
        <button onclick="compute()">Compute Interest</button>
        <br/>
        <br/>
        <span id="result"></span>
        <br/>
        <br/>

        </form>
        <br/>
        <br/>
       
        <footer>&#169; Everyone Can get Rich.<br/>This Calculator belongs to </footer>
        </div>

    </body>
    </html>

And here's the javascript:

<script>
let principalEl = document.querySelector("#principal");
let rateEl = document.querySelector("#rate");
let rateOutputEl = document.querySelector('#rate_val');
let yearsEl = document.querySelector("#years");
let formEl = document.querySelector('#form1');
let result = document.querySelector("#result");


formEl.addEventListener('submit', e => {
  e.preventDefault();
  
  if (!checkData())
    return;

  let principal = principalEl.value;
  let rate = rateEl.value;
  let year = yearsEl.value;

  let interest = principal.value * years.value * rate.value / 100;
  let amount = principal.value + interest.value;
  
  let endYear = new Date().getFullYear() + parseInt(years.value);
    
  
  result.innerHTML = `If you deposit ${principal},<br \>at an interest rate of ${rate}%<br \>You will receive an amount of ${amount},<br \>in the year ${endYear}<br \>`;
});

rateEl.addEventListener('input', e => {
  rateOutputEl.textContent = e.target.value + '%';
});
function checkData() {
  let principal = principalEl.value;
  if (!principal || parseFloat(principal) < 0) {
    alert("Enter a positive number");
    principalEl.focus();
    return false;
  }
  
  return true;
}

</script>

Answer №1

When extracting values from variables, there is no need to include .value, simply use the variable name. Although it may appear as a reference to an element with the same id in visual studio code, if 'interest' does not exist, make the necessary changes.

let interest = principal * years * rate / 100;
let amount = principal + interest;

to this:

let interest = principal * year * rate / 100;
let amount = principal + interest;

Answer №2

            <!DOCTYPE html>
            <html>
            <head>
                <title>Interest Calculation Tool</title>
            </head>
            <body>
                <div class="container">
                <h1>Interest Calculator</h1>

                <form id="form1">
                    <label for="Amount"></label>
                    Amount <input type="number" id="principal" />
                    <br />
                    <br />
                    <label for="Interest Rate"></label>
                    <label for="Interest Rate">Interest Rate</label>
                    <input
                    onchange="updateValue(this)"
                    type="range"
                    id="rate"
                    min="1"
                    max="20"
                    step="0.25"
                    default
                    value="10.25"
                    />
                    <span id="rate_val">10.25%</span>
                    <br />
                    <br />
                    <label for="No. of Years"></label>
                    No. of Years
                    <select id="years">
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                    <option value="6">6</option>
                    <option value="7">7</option>
                    <option value="8">8</option>
                    <option value="9">9</option>
                    <option value="10">10</option>
                    <!-- fill in the rest of the values-->
                    </select>
                    <br />
                    <br />

                    <label for="Calculate Interest"></label>
                    <button type="submit">Calculate Interest</button>
                    <br />
                    <br />
                    <span id="result"></span>
                    <br />
                    <br />
                </form>
                <br />
                <br />

                <footer>
                    &#169; Anyone Can get Wealthy.<br />This Calculator is the property of
                </footer>
                </div>
            </body>
            </html>
                <script>
            let principalEl = document.querySelector("#principal");
            let rateEl = document.querySelector("#rate");
            let rateOutputEl = document.querySelector("#rate_val");
            let yearsEl = document.querySelector("#years");
            let formEl = document.querySelector("#form1");
            let result = document.querySelector("#result");

            formEl.addEventListener("submit", (e) => {
                e.preventDefault();

                if (!checkData()) return;

                let principal = principalEl.value;
                let rate = rateEl.value;
                let year = yearsEl.value;

                let interest = (principal * year * rate) / 100;
                let amount = parseFloat(principal) + parseFloat(interest);

                let endYear = new Date().getFullYear() + parseInt(years.value);

                result.innerHTML = `If you deposit ${principal},<br \>at an interest rate of ${rate}%<br \>You will receive an amount of ${amount},<br \>in the year ${endYear}<br \>`;
            });

            rateEl.addEventListener("input", (e) => {
                rateOutputEl.textContent = e.target.value + "%";
            });
            function checkData() {
                let principal = principalEl.value;
                if (!principal || parseFloat(principal) < 0) {
                alert("Enter a positive number");
                principalEl.focus();
                return false;
                }

                return true;
            }
            </script>

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

Novice in AngularJS routing

Having trouble with my first AngularJS routing code. The error console isn't much help. Here is my HTML page: <body ng-app="myApp"> <div ng-controller="AppController"> <div class="nav"> <ul> <li> ...

Send a parameter to a React hook

I am facing an issue with a Component that is using a separate hook. I am unable to pass any value to that hook, which is necessary for my use case. const onEdit = (index: number) => useMediaLinkImage(img => { setNodeImages(imgData => { ...

Steps to avoid TypeError: e.target.getAttribute is not a function

My goal is to make the inner code (result) function only when a Validity attribute is present. However, my target lacks said attribute, so I'm looking for a way to use an if statement to prevent the inner code from executing. How can I avoid the Type ...

The process of running npm build is not resulting in the creation of the bundle.js file

I've read through many Q&A threads where people are facing the same issue, but I still can't figure out what's wrong with my code. When I run 'sudo npm run build', no bundle.js file is being created.** This is my code: index ...

Automatically assigning a default dynamic value to a dropdown option using Vue.js

I need to set a default selected value for the select option element, but I am facing difficulty in achieving the desired result. <template> <select v-model="tutor_work.start_year"> <option>{{tutor_work.start_year}}< ...

Discovering ways to align specific attributes of objects or target specific components within arrays

I am trying to compare objects with specific properties or arrays with certain elements using the following code snippet: However, I encountered a compilation error. Can anyone help me troubleshoot this issue? type Pos = [number, number] type STAR = &quo ...

Guide on dynamically changing the color of polymer 1.0 paper-button from an array of colors

I have an array called buttonColors that contains a set of colors in hex format. I am looking to create paper-buttons, each with the color from the buttonColors array. How can I achieve this in Polymer 1.0? <template is="dom-repeat" items="{{buttonCo ...

Trouble encountered in PHP: Generating a file from POST data and initiating download prompt for the user not functioning as intended

On my webpage, users fill out forms and input fields, which are then sent to a PHP page via Ajax and $_POST. The PHP file successfully writes the output to a txt file. However, I'm facing an issue trying to prompt the user to download the file on the ...

Having trouble with testing axios web service promises to return results using Jest in a Vue.js application

In the process of developing a new application with Vue.js and axios, I am focusing on retrieving stock market details based on company names. To kickstart the application, I am compiling all the names of US-based S&p 500 companies into a JavaScript ar ...

Tips for personalizing the tooltip on a line chart in Vue.js using Chart.js

Attempting to create a line graph using chart js and vue, but new to both technologies. In the chart below, I am trying to change the tooltip to display "10 Answers July 19, 2023". I have attempted to use the beforeLabel and afterLabel options without succ ...

To modify the specified variables in data, I must deconstruct the object

Hello everyone, this is my debut post. I am seeking assistance with destructuring in order to update a variable that is defined within the "data" section. Below are the code snippets I have been working on using Vue. data: () => ({ id: '' ...

Is it possible to utilize Jsoup to extract specific portions of JavaScript code from a webpage?

I am looking to extract data from the following script: $(document).ready(function(){ $("#areaName").val(1);$("#state").val(29);$("#city").val(1); $("#subareaName").val(1);$("#lane").val(1); } Specifically, I need to retrieve values such as areaName ...

There was a hiccup in the camera positioning as the tweening began

I've been working on a basic program that involves tweening the camera to a specific position. The functionality works smoothly for the most part, however, I encounter some glitches at the start of the transition when trying to pan the camera using or ...

The canvas element automatically removes itself after being resized within an HTML5/JavaScript environment

I created a canvas that is interactive and responsive to screen size. However, I encountered an issue where the canvas clears itself when the browser is resized by just one pixel. Is there a way to prevent this from happening? I have included code in my sc ...

Convert JSON objects within an array into HTML format

Is there a way to reformat an array of JSON objects that has the following structure? [{"amount":3,"name":"Coca-Cola"},{"amount":3,"name":"Rib Eye"}] The desired output in plain HTML text would be: 3 - Coca-Cola 3 - Rib Eye What is the best approach to ...

Why does the method Array.concat on an extended class remove empty values in Node.js version 8.9.3?

I am experimenting with adding new functionality to Arrays in node.js without altering the original Array class to avoid any unintended consequences in other modules. During testing, I encountered some failures which led me to discover that the behavior o ...

Navigating through React-router with multiple child elements

Creating one of my routes requires the presence of two children in order to function properly. The main application page, where I set up all the routes, might look something like this: <Route path="/logs" component={Logs}> <Route path="/logs ...

Adjusting body styles in a NextJS application using localStorage prior to hydration: A step-by-step guide

If you visit the React website and toggle the theme, your choice will be saved in localStorage. Upon refreshing the page, the theme remains persistent. In my NextJS project, I am attempting to achieve a similar outcome by applying styles to the body eleme ...

Issue with Jquery Conflict in WordPress

Apologies if my inquiry is not up to standard. I am currently utilizing a Google library in my project. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> The issue arises when this conflicts with the jQuery u ...

invoke a managed bean to execute JavaScript code

I am facing an issue while trying to clear a hidden form value in a JSF page from a managed bean class. I tried calling a method where I used the following code snippet to call JavaScript, but unfortunately it throws a java.lang.NullPointerException. The c ...