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.
- 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
- 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
}
- 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()}`;
}
}
- 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!