What's the best way to insert a new object into an array every time I execute a function?

I want to implement a system that creates an object and adds it to an array whenever new data is entered and the 'add' button is pressed. However, I'm unsure of the correct way to add a new object to an array. Also, for some reason, my code is not displaying in the yellow box.


var products = [];

class Product {

    constructor(productname, cost, quantity){
        this.productname = productname;
        this.cost = cost;
        this.quantity = quantity;
    }

}

function addProduct(){

    var productname = document.getElementById('productName').value;
    var cost = document.getElementById('cost').value;
    var quantity = document.getElementById('quantity').value;

    tbody += '<tr><td>' + productname + '</td><td>' + cost + '</td><td>' + quantity + '</td><td>' + test + '</td><tr>';

      document.getElementById('tablebody').innerHTML = tbody;

      product();

     function product(){
        products.push(new Product(productname, cost, quantity));
     }
}

Answer №1

When you invoke product, you are actually overriding the variable products. To avoid this, utilize push and make sure to pass the variables into product to prevent any errors:

    product(productname, cost, quantity);

}

function product(productname, cost, quantity) {
    products.push(new Product(productname, cost, quantity));
}

Additionally, remember to properly close your addProducts function with a closing brace:

    document.getElementById('tablebody').innerHTML = tbody;

    product();

}

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

Performing AJAX callback function on success in jQuery

I've been trying to troubleshoot an error but none of the solutions I've found so far seem to be working for me. I have an ajax request set up to retrieve JSON data from the server. I can see the JSON data that I want to capture when using consol ...

Retrieve the input value using send keys and display it in the console using Selenium WebDriver

I am currently working on a project where I am integrating the Selenium Webdriver with the Chrome implementation in Javascript. The project involves testing a simple quantity input form, and I am struggling with a particular aspect of it. My challenge lies ...

What is the best way to display the outcome in a popup window?

I am looking to display the result in a pop-up window. Code: <?php $con=mysqli_connect("localhost","root","1234","fyp"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $result = ...

Removing the switcher outline in Bootstrap Switch: a step-by-step guide

I have implemented the bootstrap-switch - v3.3.1, however, I want to remove the default blue outline that appears around the switcher when toggling it on or off. Despite setting style="outline: 0 none; for the input, the outline remains visible. Below is ...

Using AngularJS with the Chosen Plugin to pre-select a value in a dropdown menu

After following the guidance from this URL, I successfully incorporated the chosen plugin into Angular.js. Now that I can retrieve the value, my next objective is to have the selected value be pre-selected in the chosen dropdown menu. If anyone has a sim ...

Custom ID in Firebase Firestore is not generating a new document even after successfully creating a new user

In my Vue App, I designed a registration form to automatically create a Firestore document linked to the User UID with a unique document ID. Although the user creation process is successful, the document creation fails without showing any errors in the c ...

"Exploring the process of integrating angular-xeditable into a MeanJS project

I recently attempted to install angular-xeditable from the link provided, but encountered issues while trying to reference the JavaScript files in layout.html after downloading it with bower. According to the documentation, these files should be added auto ...

Tips on concealing all classes except one through touch swiping

If you have a website with a single large article divided into multiple sections categorized as Title, Book1, Book2, & Book3, and you want to implement a swipe functionality where only one section is displayed at a time, you may encounter some issues. ...

Can you explain the role of "use-cases" within the framework of Clean Architecture?

I'm currently working on implementing the Clean Architecture structure in my app, but I'm struggling to clarify the different components. For instance, it seems like the entities in my application are Employee, Department, EmployeeSkill, which h ...

Creating a Popup Window in React JS that Functions Like Gmail's New Message Interface

I am looking to implement a 'pop-up window' with close and minimize functions similar to the one utilized by Gmail for new messages within my react js application. Any suggestions on how to achieve this? This component needs to remain visible ev ...

leveraging hooks in NextJS app router for static page generation

How can I make an action take effect on page-load for the app router equivalent of statically generated pages from static paths in NextJS? Everything is working fine with my page generation: // app/layout.js import Providers from '@/app/Providers&apo ...

How can I iterate through JSON data and showcase it on an HTML page?

I am in the process of developing a weather application using The Weather API. So far, I have successfully retrieved the necessary data from the JSON and presented it in HTML format. My next goal is to extract hourly weather information from the JSON and ...

Enhance the efficiency of React code by optimizing the loading of data from multiple sources concurrently instead of one after another

In my project, there are 2 tabs displaying visualizations generated from separate data sources. Each tab requires multiple queries to be executed in the background to fetch the data, resulting in a delay when loading each tab individually. The current impl ...

Importing a form input as a constant in an API endpoint script

Recently stepping into the realm of React, I'm encountering difficulties in my Next.js app related to imports and exports. My goal is to export a const from a form component to an API endpoint for use within a function. While I can see the form compo ...

When capturing photos using h5 on iOS devices, the browser may experience a flash back issue

I have been searching Baidu and Google for a while now, but I still haven't found a solution. Here is the specific issue: When using h5 to take photos on iOS systems, the browser flashes back. HTML Code <img src="xxx" onclick="sta ...

Tips for utilizing a variable name with ajax in jQuery

Currently, I have the following code that is a part of an autocomplete ajax query. The code is returning JSON and is functioning correctly with the provided code snippet. However, my goal is to enhance the auto complete function by making it more generic ...

Navigate through fabricated data not appearing in Express application

I have come across a handlebars template file within my Express app: {{#each data}} <article class="id-{{this.id}}"> <h1><a href="/journal/{{this.url}}">{{this.title}}</a></h1> <p>{{this.body}}</p> </ar ...

Exploring the concepts of arc functions in discord/js programming

Example: Having trouble understanding how to create an arc in JavaScript based on a percentage input? Here's a simple explanation: feed it a percentage and it will create an arc that represents that percentage of a circle. I've managed to get t ...

Creating unique parent-children category groupings in Excel VBA using collections and dictionaries - how can it be done?

Could someone assist me in understanding how to consolidate data by hierarchical groupings using VBA? PivotTables and tables are not feasible due to user constraints. The data includes three levels of groupings: Parent, Child, and Grain. Parents may have ...

How can the selected value be shown in the dropdown menu after moving to a different webpage in HTML?

My application features 4 roles displayed in a dropdown menu. When a specific role is clicked, it should go to the corresponding href link that was specified. However, I encountered an issue where after navigating to the second HTML page, the selected rol ...