Error: Unable to access 'amtSavingsInput' variable before it has been initialized

I encountered an issue with form3/chart3 while trying to replicate the success of form1/chart1 and form2/chart2. Despite following the same steps and structure, form3/chart3 seems to be malfunctioning. The error message I'm receiving is "Uncaught ReferenceError: can't access lexical declaration 'amtSavingsInput' before initialization."

Below is the code snippet for form3/chart3:

// The code for form3/chart3 goes here...

Accompanied by a simple HTML bootstrap form:

  <div class="col-md-6">
                <h2>Savings and Investments</h2>
                <p>Growing wealth is about holding onto money. Choose how much of your £<span class="inline-block"
                        id="cashLeftDisplay2"></span> (cash leftover) that you will save or invest.</p>
                <form> <!-- Savings & Investments form-->
                    <div class="mb-3">
                        <label for="amt_Savings" class="form-label">Amount in a Savings Account</label>
                        <input type="text" class="form-control" id="amt_Savings" value="0" placeholder="0">
                      </div>
                      <div class="mb-3">
                        <label for="yield_Savings" class="form-label">Yearly Interest % Earned</label>
                        <input type="text" class="form-control" id="yield_Savings" value="0" placeholder="0">
                      </div>
                      <div class="mb-3">
                        <label for="amt_Vanguard" class="form-label">Amount in Vanguard Account</label>
                        <input type="text" class="form-control" id="amt_Vanguard" value="0" placeholder="0">
                      </div>
                      <div class="mb-3">
                        <label for="yield_Vanguard" class="form-label">Benchmark % Return</label>
                        <input type="text" class="form-control" id="yield_Vanguard" value="0" placeholder="0">
                      </div> 
                </form>
                <button class="btn btn-primary" id="nextButton">Next</button>
            </div>

Answer №1

No issues were found with the code, it just needs to include the canvas element. The code runs smoothly without any errors

let amtSavingsInput = document.getElementById('amt_Savings');
let yieldSavingsInput = document.getElementById('yield_Savings');
let amtVanguardInput = document.getElementById('amt_Vanguard');
let yieldVanguardInput = document.getElementById('yield_Vanguard');

// Locate the cashInChart canvas element
const moneyMapChartElement = document.getElementById('moneyMapChart');

// Provide initial chart data
const chart3 = {
  labels: ['1', '2', '3', '4', '5'],
  datasets: [
    {
      label: '',
      data: [],
      backgroundColor: 'rgba(75, 192, 192, 0.6)',
      borderWidth: 1
    }
  ]
};

// Create the chart
const moneyMapChart = new Chart(moneyMapChartElement, {
  type: 'bar',
  data: chart3,
  options: {
    responsive: false,
    scales: {
      y: {
        type: 'linear', // Scale type set to 'linear'
        beginAtZero: true
      }
    }
  }
});

// Function to calculate and update the chart
function updateChart() {
  let amtSavings = parseFloat(amtSavingsInput.value);
  let yieldSavings = parseFloat(yieldSavingsInput.value);
  let amtVanguard = parseFloat(amtVanguardInput.value);
  let yieldVanguard = parseFloat(yieldVanguardInput.value);

  // Convert monthly savings to yearly savings
  amtSavings *= 12;
  amtVanguard *= 12;

  const years = 5; // Desired number of years

  const capitals = calculateCapitalGrowth(amtSavings, yieldSavings, amtVanguard, yieldVanguard, years);

  // Update the chart data
  moneyMapChart.data.datasets[0].data = capitals;
  moneyMapChart.update();
}

// Add event listeners to input fields
amtSavingsInput.addEventListener('input', updateChart);
yieldSavingsInput.addEventListener('input', updateChart);
amtVanguardInput.addEventListener('input', updateChart);
yieldVanguardInput.addEventListener('input', updateChart);
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
 <div class="col-md-6">
                <h2>Savings and Investments</h2>
                <p>Growing wealth is about holding onto money. Choose how much of your £<span class="inline-block"
                        id="cashLeftDisplay2"></span> (cash leftover) that you will save or invest.</p>
                <form> <!-- Savings and Investments form-->
                    <div class="mb-3">
                        <label for="amt_Savings" class="form-label">Amount in a Savings Account</label>
                        <input type="text" class="form-control" id="amt_Savings" value="0" placeholder="0">
                      </div>
                      <div class="mb-3">
                        <label for="yield_Savings" class="form-label">Yearly Interest % Earned</label>
                        <input type="text" class="form-control" id="yield_Savings" value="0" placeholder="0">
                      </div>
                      <div class="mb-3">
                        <label for="amt_Vanguard" class="form-label">Amount in Vanguard Account</label>
                        <input type="text" class="form-control" id="amt_Vanguard" value="0" placeholder="0">
                      </div>
                      <div class="mb-3">
                        <label for="yield_Vanguard" class="form-label">Benchmark % Return</label>
                        <input type="text" class="form-control" id="yield_Vanguard" value="0" placeholder="0">
                      </div> 
                </form>
                <button class="btn btn-primary" id="nextButton">Next</button>
            </div>
<canvas id=moneyMapChart></canvas> <!-- <== Added! -->

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

Avoid filling the container with an excessive amount of grids while maintaining the correct aspect ratio

I encountered a situation where I needed to dynamically create a grid with square grids of dimensions MxN. Below is the code snippet for achieving this: rerender = (event) => { const height = document.getElementById("y-input").value; const width ...

Using AngularJS to display a targeted row in a table

I am currently working with a basic table and using ng-repeat to display rows in the table. I have a specific requirement where I want to show an additional row when a regular row is clicked. This additional row should contain custom markup in just one co ...

Using D3.js for Page Navigation

For my D3 bar charts, I am working with a substantial amount of JSON data obtained from an API. My goal is to display only 10-20 bars at a time. Would it be possible to implement pagination using D3 itself, or should I explore alternative methods (such a ...

Issue encountered with Cheerio while using Node.js

When attempting to parse code using cheerio and request on Node Js, I am encountering an error undefined. After thorough checking, it became apparent that the error lies within cheerio rather than the request component. Here is a snippet of my parsing code ...

Error message: AngularJS Jasmine spyOn: number has no functionality

I am encountering difficulties while attempting to execute a test that utilizes a mockup for a service call (retrieving location data from a web SQL database). Below is the controller code: .controller('LocationDetailCtrl', function ($scope, $s ...

Despite making changes, the React Element continues to be rendered

I am a beginner in React and facing an issue with my simple app My aim is to implement a search functionality, but the problem arises when I search for an element - all search results are displayed After clearing the search box, all elements appear as in ...

Anticipating the arrival of the requested data while utilizing Ajax sending

Greetings, I'm currently utilizing JavaScript to send a request and receive a response from the server. xxmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); myotherMethod(); I am looking for a way to ensure that the next set of instructions ar ...

What is the best way to display a header element in front of an article element?

I'm struggling with making my header element sticky and appear in front of my article. Modifying the z-index hasn't given me the desired result so far. Is the z-index ineffective when dealing with floating elements? Or is there a workaround to m ...

The try and catch block in JavaScript is failing to correctly capture the HTTP status

I have a function that successfully posts JSON to an API endpoint. Here is the code I am using: function sendValuesPageLoad(){ var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { try { if (xhr.readyState === ...

Checkbox Selection - Modify Prompt to "Kindly mark this box to continue"

I have created a multi-select checkbox form, and I've added some JavaScript to ensure that the visitor selects at least one option <div class="form-group options"> <label class="control-label col-md-4" for="optiontext">Specify an option&l ...

Mobile Chrome allows users to utilize the IFrame player API for enhanced video

Currently, I am working on creating a mobile website where I plan to include some YouTube videos using the IFrame player API (https://developers.google.com/youtube/iframe_api_reference). My main goal is to have the video start playing only after the user ...

Incorporating text sections into a div container and adjusting the width

Currently facing an issue with the canvas element on my project. <div id="app-container"> <div id="canvas-container"> <div id="canvas"></div> </div> </div> In the CSS stylesheet, the following styles ar ...

Adjusting image width using jQuery

I have been experimenting with creating a Webgl hover effect for an image. The effect works well, but now I am trying to specify a width for the image within jQuery. new hoverEffect({ parent: document.querySelector('.ticket'), intensity1: 0. ...

Implementing dynamic page loading with ajax on your Wordpress website

I'm currently facing an issue with loading pages in WordPress using ajax. I am trying to implement animated page transitions by putting the page content into a div that I will animate into view. However, my current logic only works correctly about 50% ...

Retrieve Browser Screen Width and Height using MVC3 Razor in the View

I am facing a challenge on my website where I need to generate a Bitmap dynamically and ensure it is rendered according to the width and height of the browser so that there are no overflow issues on the page. Although I have successfully created an image ...

"Unable to locate the specified file or directory" error message pops up while attempting to save a file

Currently, I am in the process of generating a JSON file using my website with intentions to deploy it later. Below is the code snippet that I have implemented: saveFile = (i, data) => { var filename = `${i}_may.json`; var folder_list = ["desktop", ...

Determine the amount of time that can be allocated based on the attributes contained within the object

I am faced with a JSON structure like the one below: var meetings = [ { id: '1', start_time: "2020-11-15T08:30:00+00:00", end_time: "2020-11-15T14:15:00+00:00" }, { id: '2', start_time: &quo ...

Creating toggling elements in Vue.js using dynamic v-show based on index and leveraging falsey v-if

What is the most effective way to use v-show for toggling elements based on their index? I have been able to toggle the elements, but when you click on the element that is already open, it does not close. <div v-for="(btn, index) in dataArray"> ...

To enable the radio button upon clicking the list item in JavaScript, simply check the radio button

I am working with radio buttons Here is the HTML code: <input type="radio" class="first" name="bright" checked> <input type="radio" class="second" name="bright" > <input type=" ...

Setting the value for a textbox using Jquery's .val() function works, while .attr() does not have the

//unable to get it working $("#TextBoxID1").attr("value","HI Value Change") //works perfectly fine $("#TextBoxID2").val("HI Value Change") <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <input type= ...