Non-responsive behavior triggered by a button click event (JavaScript)

Help needed with displaying results on the same page for an online calculator I'm creating.

Why are the results not showing up as expected?

I want users to input 4 pieces of information, have the logic executed, and then display the answers below the page... How do I achieve this?

function calculate(event) {
  event.preventDefault(); // prevent form submission from reloading the page

  // Get input values
  const name = document.getElementById('name').value;
  const age = parseInt(document.getElementById('age').value);
  const yearsToRetire = parseInt(document.getElementById('years-to-retire').value);
  const passiveIncome = parseInt(document.getElementById('passive-income').value);

  // Calculate results
  const inflationRate = 0.025;
  const yearsToInvest = yearsToRetire - (age >= 60 ? 0 : yearsToRetire);
  const passiveIncomeTarget = passiveIncome / 0.95;
  const futureValueTarget = passiveIncomeTarget * ((1 + inflationRate) ** yearsToInvest);

  // Prepare result strings
  const passiveIncomeTargetFormatted = formatCurrency(passiveIncomeTarget);
  const futureValueTargetFormatted = formatCurrency(futureValueTarget);

  // Display results
  const resultsDiv = document.getElementById('results');
  resultsDiv.innerHTML = `
    <h2>Results for ${name}</h2>
    <p>Your target passive income is <strong>${passiveIncomeTargetFormatted}</strong> per year.</p>
    <p>To achieve this, you need to have a total of <strong>${futureValueTargetFormatted}</strong> in investments.</p>
  `;
}

function formatCurrency(amount) {
  return '$' + amount.toLocaleString('en-US', {
    minimumFractionDigits: 0,
    maximumFractionDigits: 0
  });
}

const form = document.getElementById('calculator');
form.addEventListener('submit', calculate);
body {
  font-family: Arial, sans-serif;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  text-align: left;
}

h1 {
  text-align: center;
  font-size: 36px;
  margin-bottom: 30px;
}

form {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 20px;
  margin-bottom: 30px;
}

label {
  font-size: 18px;
  margin-bottom: 5px;
}

input[type="number"],
input[type="text"] {
  font-size: 18px;
  padding: 5px;
  border-radius: 5px;
  border: 1px solid #ccc;
  width: 100%;
}

button[type="submit"] {
  font-size: 18px;
  background-color: #4CAF50;
  color: #fff;
  padding: 10px 20px;
  border-radius: 5px;
  border: none;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

button[type="submit"]:hover {
  background-color: #3e8e41;
}

#results {
  display: none;
  margin-top: 30px;
  font-size: 24px;
}

#results p {
  margin: 10px 0;
}

#results table {
  width: 100%;
  margin-top: 20px;
  border-collapse: collapse;
}

#results th,
#results td {
  padding: 10px;
  border: 1px solid #ccc;
}

#results th {
  background-color: #f2f2f2;
  font-weight: bold;
  text-align: left;
}
<div class="container">
  <h1>Calc</h1>
  <form id="calculator">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>

    <label for="age">Age:</label>
    <input type="number" id="age" name="age" min="0" max="120" required>

    <label for="yearsToRetire">Years Until Retirement:</label>
    <input type="number" id="yearsToRetire" name="yearsToRetire" min="1" max="50" required>

    <label for="passiveIncome">Desired Passive Income in Retirement:</label>
    <input type="number" id="passiveIncome" name="passiveIncome" min="0" required>

    <button onclick="calculate()">Calculate</button>
  </form>

  <div id="results"></div>
</div>

Answer №1

  1. Make the necessary adjustments to the button by removing the onclick attribute and changing the type to submit.
  2. The elements with ids of years-to-retire and passive-income do not exist, so use selectors yearsToRetire and passiveIncome instead.

Check out this code snippet:

function formatCurrency(amount) {
  return '$' + amount.toLocaleString('en-US', {
    minimumFractionDigits: 0,
    maximumFractionDigits: 0
  });
}

document.getElementById('calculator').addEventListener('submit', function(event) {
  event.preventDefault(); // Prevent form submission from reloading the page

  // Get input values
  const name = document.getElementById('name').value;
  const age = parseInt(document.getElementById('age').value);
  const yearsToRetire = parseInt(document.getElementById('yearsToRetire').value);
  const passiveIncome = parseInt(document.getElementById('passiveIncome').value);

  // Calculate results
  const inflationRate = 0.025;
  const yearsToInvest = yearsToRetire - (age >= 60 ? 0 : yearsToRetire);
  const passiveIncomeTarget = passiveIncome / 0.95;
  const futureValueTarget = passiveIncomeTarget * ((1 + inflationRate) ** yearsToInvest);

  // Prepare result strings
  const passiveIncomeTargetFormatted = formatCurrency(passiveIncomeTarget);
  const futureValueTargetFormatted = formatCurrency(futureValueTarget);

  // Display results
  const resultsDiv = document.getElementById('results');
  resultsDiv.innerHTML = `
        <h2>Results for ${name}</h2>
        <p>Your target passive income is <strong>${passiveIncomeTargetFormatted}</strong> per year.</p>
        <p>To achieve this, you need to have a total of <strong>${futureValueTargetFormatted}</strong> in investments.</p>
      `;
});
body {
  font-family: Arial, sans-serif;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  text-align: left;
}

h1 {
  text-align: center;
  font-size: 36px;
  margin-bottom: 30px;
}

form {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 20px;
  margin-bottom: 30px;
}

label {
  font-size: 18px;
  margin-bottom: 5px;
}

input[type="number"],
input[type="text"] {
  font-size: 18px;
  padding: 5px;
  border-radius: 5px;
  border: 1px solid #ccc;
  width: 100%;
}

button[type="submit"] {
  font-size: 18px;
  background-color: #4CAF50;
  color: #fff;
  padding: 10px 20px;
  border-radius: 5px;
  border: none;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

button[type="submit"]:hover {
  background-color: #3e8e41;
}

#results {
  /*      display: none;*/
  margin-top: 30px;
  font-size: 24px;
}

#results p {
  margin: 10px 0;
}

#results table {
  width: 100%;
  margin-top: 20px;
  border-collapse: collapse;
}

#results th,
#results td {
  padding: 10px;
  border: 1px solid #ccc;
}

#results th {
  background-color: #f2f2f2;
  font-weight: bold;
  text-align: left;
}
<div class="container">
  <h1>Calc</h1>
  <form id="calculator">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>

    <label for="age">Age:</label>
    <input type="number" id="age" name="age" min="0" max="120" required>

    <label for="yearsToRetire">Years Until Retirement:</label>
    <input type="number" id="yearsToRetire" name="yearsToRetire" min="1" max="50" required>

    <label for="passiveIncome">Desired Passive Income in Retirement:</label>
    <input type="number" id="passiveIncome" name="passiveIncome" min="0" required>

    <button type="submit">Calculate</button>
  </form>

  <div id="results"></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

Jenkins encountered an issue where script execution was blocked on <URL> due to the document's frame being sandboxed without the 'allow-scripts' permission set

When using an iFrame in HTML, it's always best to remember to sandbox it and set the 'allow-scripts' permission to true. However, I'm facing an issue in my pure Angular JS application where there is no iFrame present. It runs smoothly ...

The dynamics of Express.js functionalities

I am seeking to better understand how flow functions within an Express app using Routes, with the following set of Routes: app.use(require('./routes/reportsRouter')); app.use(require('./routes/crewsRouter')); app.use(require('./ro ...

Interested in trying out Express and socket.io for chatting?

I've successfully set up the chat application, but now I'm faced with a dilemma: how can I make the chat work on the default port:80, where my main site is hosted? One solution that comes to mind is using an iframe - but is there another way? B ...

How to Update Font in Android Studio WebView

I am facing an issue with HTML: I am trying to implement a custom font in a webview but the font does not change when using this code: public void loadHTLMContentText(String text, WebView view) { String body; String head = "<head><style ...

Accessing and displaying a randomly selected PDF file from a directory using HTML coding

Welcome to my recipe collection website where I document all the delicious recipes I love to eat. One feature I would like to add is a 'random' button, so that a recipe will be selected at random for me without having to make a decision. Althou ...

Is it appropriate for a search service to provide a 404 response?

In the world of web development, let's say I have a server-side search feature that is triggered by JavaScript (AJAX). What happens if I search for something like "chewy dragees", and although the server successfully receives the search request, it do ...

The alignment of list bullets is inconsistent across different web browsers

Check out this code snippet on JSFiddle: http://jsfiddle.net/PZgn8/8/. It's interesting to see how the rendering differs between Chrome 27 and Firefox 21. Despite the difference, I believe Firefox is actually displaying the desired outcome. <ul st ...

Is there a method in Discord.JS to remove an embed from a message sent by a user?

Currently, I am developing a bot utilizing the Discord.JS API. This bot is designed to stream audio from specific YouTube links using ytdl-core. Whenever a link is typed in, an embed of the YouTube video appears. While there are methods to disable embeds o ...

Exploring the functionality of the readline module using a simulated command-line

I am currently working on developing a unit test for a module that utilizes the "readline" functionality to interpret standard input and provide standard output. Module: #!/usr/bin/env node const args = process.argv.slice(2) var readline = require(' ...

Angular click directive

Exploring AngularJS and attempting to modify an example from a tutorial. I want the ng-init value to be equal to the value passed from a script function. How can I achieve this? Here's the code snippet: <html> <body> <h2> ...

Incorporating React.js with a server API that doesn't use JavaScript

My upcoming project involves enhancing my current application frontend by implementing React.js. The existing frontend currently utilizes standard REST calls to communicate with a server built using Microsoft technologies, and there are no plans of changin ...

Looking for a resolution? Ensure that actions are plain objects by employing custom middleware specifically designed for managing asynchronous actions

I'm attempting to replicate a MERN stack project named Emaily, but I've encountered an error Error: Actions must be plain objects. Use custom middleware for async actions. Here is the code for my Action: import axios from 'axios'; im ...

When the button is clicked, I desire to reveal the background color of a specific div

<div class="mat-list-item" *ngIf="authService.isAdmin()" (click)="openModal('site-settings', site.siteID)"> <span class="mat-list-item-content">{{ "Application.site_settings_label&q ...

Tips on integrating TypeScript into JavaScript

Currently, I am working with a node.js server.js file. var http = require('http'); var port = process.env.port || 1337; http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res ...

The alignment is off

<script> var myVar = setInterval(myTimer, 1000); function myTimer() { var d = new Date(); document.getElementById("demo").innerHTML = d.toLocaleTimeString(); } </script> <p text-align="right" id="demo" style="font-family:Comic Sans ...

Send form using AJAX with a callback function

I need help figuring out how to submit a form when a captcha is clicked. I attempted to use my own jQuery function, but unfortunately it's not working. Could someone please take a look at my code and let me know what's wrong with it? Javascript ...

The hamburger symbol (&#9776;) appears as a dull shade on Android screens

Imagine a basic website design featuring a gray background with white text. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> </head> <body style="background: gray; color: white; font-size:50px;" > The t ...

The functionality of a Google chart is determined by the value of the AngularJS $scope

I recently started working with AngularJS and Google charts. I've successfully created a Google chart using data from AngularJS. It's functioning properly, but now I want to make the chart dynamic based on my Angular Scope value. I have a filter ...

Secure your API routes in NextJS by using Passport: req.user is not defined

Currently, I am utilizing NextJS for server-side rendering and looking to secure certain "admin" pages where CRUD operations on my DB can be performed. After successfully implementing authentication on my website using passport and next-connect based on a ...

The background size cover feature is not functioning properly on mobile devices, especially on longer pages

In my Next.js project, I am encountering an issue with the background image not displaying on longer pages when viewed on a Google Pixel 3a device. Here is how it looks on shorter pages that do not exceed the viewport height: https://i.sstatic.net/jJBTy.pn ...