When calling an array's values from another function, the values seem to mysteriously vanish in Javascript

I am currently working on creating a form using JavaScript that needs to perform two key functions:

1) Dynamically adding elements to a list

2) Identifying a specific element (e.g. the one with the highest value) upon button click

To visualize what I have done so far, here are some images of my progress: Image 1

The first functionality of adding elements dynamically is functioning correctly as expected. However, the second functionality of identifying the element with the highest value is not working as intended. This was my approach:

1) Whenever an element is added to the list, it is also stored as an object of the class "installation" in an array called installations = []

2) Upon clicking the "Identify Longest Duration" button, I loop through the installations array using a map function to identify and display the element with the highest value as an alert.

Unfortunately, when I attempt to access the installations array from another function, it appears to be empty.

  1. Extract values from the form fields
var instStorage = document.getElementById("instStorage");
var instMasse = document.getElementById("instMasse");
var instPrice = document.getElementById("instPrice");
var instDischarge = document.getElementById("instDischarge");
const installations = [] ; // initialize an empty installations array

  1. Add values to the DOM, Call a separate function to add values to the installations array

const createInstallation = () =>  {

    ... (working code to append variables from step 1 to list element in DOM)... 
    addInstallation(); // call another function to add installation to installations array

}

  1. Class Definition for installation objects

class installation {
    constructor(storage, masse, price, discharge) {
        this.storage = storage;
        this.masse = masse;
        this.price = price;
        this.discharge = discharge; 
    }
    ... (includes getter functions) ...

    summary = () => {
        return `Installation Specifications: Storage ${this.getStorage()}, Mass ${this.getMasse()}, Price ${this.getPrice()} and Discharge Rate ${this.getDischarge()}`;

    }

}
  1. Add installation to installations array
const addInstallation = () => {

    installations.push(new installation(instStorage, instMasse, instPrice, instDischarge));
    (...)

}

For testing purposes, when I call the summary function inside createInstallation() function (after calling addInstallation()), everything works fine - the first element of the installations array is displayed accurately:

alert(installations[0].summary());

However, when I attempt to do the same from the event listener of the "Identify Longest" button, the installations array suddenly becomes empty, despite having added an element just moments before. It seems like a scope issue, but I am struggling to pinpoint how to resolve it. Any assistance would be greatly appreciated!

Thank you for your help!

Answer №1

Retrieve values from a form

var instStorage = document.getElementById("instStorage");

What seems to be the issue is that getElementById() only retrieves the element itself, not its value.
If instStorage and other elements are input elements (although this is not confirmed), you should modify the code to actually retrieve their value:

var instStorage = document.getElementById("instStorage").value;
var instMasse = document.getElementById("instMasse").value;
var instPrice = document.getElementById("instPrice").value;
var instDischarge = document.getElementById("instDischarge").value;

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

Leveraging Ajax and jQuery to create a POST request for adding a new record to a MySQL table within a Node.js server

My form is designed to collect user information like name, age, and more. The aim is to submit this data from the client side, inserting it into a MySQL table row. However, I'm facing difficulties in getting the data to successfully insert. Below are ...

Guide to implementing 'active' state in Bootstrap 4 using JavaScript on a basic PHP website

A simple website consisting of three pages, designed using Bootstrap 4 framework. I have utilized includes to incorporate header.php and footer.php into the respective PHP pages below. My challenge lies in adding the 'active' class from Bootstrap ...

preventing the page from scrolling whenever I update my Angular view

Whenever I update a part of my model that is connected to my view, my page automatically scrolls. I suspect that the page scrolling is triggered by the view updates. How can I stop this from happening? For instance, here is an example involving a dropdown ...

What is the proper way to preload a set of objects in a list or array in NextJS?

I currently have an image displayed on one of my pages using next/image, with the priority set to true in order to eagerly load the asset from the state const [imageToUse, setImageToUse] = useState(initialImage); <Image src={imageToUse} alt='scrol ...

Angular - Uncaught TypeError: XX is not a function on the site

Seems like I might be overlooking a property somewhere, but as I'm following this project, I encountered this error in my controller. TypeError: loginService.signin is not a function This is the content of my controller.js file angular.module(&apos ...

Have you ever wondered why Vue 3 imports all JS files for every page upon the initial project load?

Is there a way to make Vue 3 import only the necessary js files for each component instead of loading all files at once when the project is first loaded? For example, if I navigate to the contact page, Vue should only import the contact.js file, rather tha ...

Why Promise.all() isn't working as expected - where am I going wrong?

Currently, I am in the process of developing a script that utilizes the GitHub API. The script includes a function that takes a list of usernames as input. Each username triggers an API request to fetch that user's starred repositories. For each starr ...

Comparing identical elements in JavaScript

Crucial Note I want to clarify that I have no intentions of scamming, phishing, or causing any harm. My goal is to develop a website magnifier similar to using a magnifier on paper. Dilemma Let me paint the picture for you. I've effectively copied ...

Automatically populate email fields with pre-filled form data

Looking to create an HTML form that utilizes JS/jQuery (no PHP) to capture data from "subject" and "message" fields and send an email. The goal is for the client-side code to open the user's mail client, pre-fill the subject and body with form data, a ...

show the array as an image using the mean stack technology, which includes node.js and Angular

My persona has an attribute retrieved from MongoDB known as "faceDetection.photo", which is an array of values. Here is a snippet of the code: persona.faceDetection.photo=[255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,1....etc] var encodedData = window.btoa( ...

Utilizing a router to control a GET request for accessing an image file

Currently utilizing node.js in conjunction with the express framework, I am attempting to initiate a get request for an image by appending it to the body through $('body').append('<img src="images/image.gif?34567">'). Despite rece ...

Ensure that the query is properly separated from the body when making an Axios request

While working on my code, I encountered an issue when making a PUT request to the backend of the application using Axios. The problem arose when the method in the user service, responsible for handling the request, returned a null response. Here is the met ...

Can the following VBScript be converted into JavaScript?

I'm in the process of converting some VBScript to JavaScript, but I'm unsure if it's feasible due to its reliance on Microsoft apps and code. I am seeking assistance with either: a) converting the code to JavaScript successfully, or b) deter ...

Node.js: Passing a URL as a Parameter

Snippet: app.get("/:url", function(req,res) { var url = req.params.url; res.send(url); }); Issue: The provided code snippet is not functioning as expected. When attempting to access: http://localhost:3000/https://www.google.com An error messa ...

transforming the use of getelementbyid into a plural form

Can a getElementById function work in plural context? Or would I need a different function or maybe jQuery? <script type="text/javascript> window.onload = function() { var test = document.getElementById('test'); if ...

Redirect to a new page following a toastr notification in an Angular application

Looking for a way to automatically navigate to another page after a toastr notification disappears. showToasterWarning(){ this.notifyService.showWarning("No Data Found for this Date!", ""); } The notifyService is responsible ...

WebStorm: React and Bootstrap autocomplete feature fails to function

After installing React and Bootstrap in WebStorm, I encountered an issue where the Bootstrap code highlighting was not working. Despite JSX functioning correctly, the problem with Bootstrap remains unresolved. Can anyone provide guidance on how to resolve ...

Take a sequence of multiple words and combine them into a single string with hyphens in between

I've been working on a WordPress website and I created a JavaScript function that adds a class to the body tag, allowing for different backgrounds based on the category. It works perfectly fine when the category is a single word, but encounters issues ...

Tips for resizing the background to match the font size on a canvas marker in Google Maps

Check out my jsFiddle code below: var marker = new google.maps.Marker({ position: new google.maps.LatLng(-25.363882,131.044922), map: map, title:"Hello World!", icon: CanvasCrear("hola", 15) ...

The reactivity of a Vue.js computed property diminishes when it is transmitted through an event handler

Within my main application, I've implemented a Modal component that receives content via an event whenever a modal needs to be displayed. The Modal content consists of a list with an associated action for each item, such as "select" or "remove": Vue. ...