How to Populate a New Array in Javascript with Additional Items

Currently in the process of learning Javascript and working on creating a cart feature. Utilizing a drop-down menu to choose items from an array, I intend to then add the selected item to an empty array named "cart".

Below is the code snippet responsible for selecting data from the catalog array to push it into the cart array:

let addFCat = document.getElementById('addfromCat');

function cat_Cart(){ 

  // Determine the index of the loaded item
  let e = document.getElementById("productList");
  let itemIndex = e.options[e.selectedIndex].value;
  console.log(itemIndex);

  // Add item to cart
  cart.push(catalog[itemIndex]);
  localStorage.setItem("cart", JSON.stringify(cart));

  // Display update alert
  // alert(`You added ${cartItems.name} to your Cart`)

}

However, despite implementing the function, my cart[] array remains empty.

If I manually type: cart.push(catalog[enter index here]) in the console, as well as: cart.length; the cart updates accordingly. What could be causing my cart not to update within the function?

(PS. Using console.logs to verify the implementation of the code)

Answer №1

It seems that when you refresh your browser, it empties your cart[], so I recommend storing the cart array in an empty condition in localStorage first, and then retrieving the updated value like this:

const cart = []

localStorage.setItem("cart", JSON.stringify(cart));

function updateCart(){ 

  const getCart = JSON.parse(localStorage.getItem("cart"));

  // Find the index of the selected item
  let e = document.getElementById("productList");
  let itemIndex = e.options[e.selectedIndex].value;
  console.log(itemIndex);

  // Add the item to the cart
  getCart.push(catalog[itemIndex]);
  localStorage.setItem("cart", JSON.stringify(getCart));

}

By using local storage, you can save data that won't be deleted when refreshing the browser. Thank you.

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

Displaying outcomes solely based on JSON upon choosing a filter

Goal I aim to only show results once their respective state is chosen. Currently, all results are displayed automatically upon page load. I prefer if nothing is shown initially. Only when a state is selected should the corresponding results appear. Bac ...

Create a cookie in javascript

There seems to be an issue with this code snippet: function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRc ...

Sleek Dialog Boxes with Bootstrap 4 - Bootbox Modal

Within the structure of my webpage, there resides a table containing various elements. One specific cell within this table holds a link that triggers jQuery scripts upon being clicked. An example action initiated by clicking this link is displaying a Boots ...

Transmit messages from server (via Expressjs routing) to the client

I am looking for guidance on how to effectively send messages from the server to the client and incorporate this functionality into routes/index.js within my mean stack project. Can anyone provide insights on using socket.io in this context?: router.post( ...

"An issue with the backend connector between ExtJS and PHP/MySQL has

Encountering a similar issue as discussed in this post Closely following the official documentation provided at Struggling to comprehend how to resolve it Edit: Here is a screenshot of Firefox Console for reference Highlighting 'api.php' (the ...

attach an event listener for the click event

I have a button set up like this Inside index.html: <body> <section> <button id="open-file">Open File</button> ...(series of other similar buttons)... </section> </body> <script> requir ...

Is there a problem with the way divs are being displayed when using jQuery to show the first 12 elements with the class "hide-show"?

I am encountering a problem with displaying data using the jQuery slice() and show() methods to reveal dynamically generated divs from a PHP function. The code is as follows: <style> .hide-show { display :none; } </style> <div class="c ...

An array containing image names allows me to change the displayed image every time I click a button in Swift

My current project includes an array called arrowArray with image names such as "up," "down," "right," and "left." I have set up an imageView and a button with an action in my storyboard. Every time I press the button, I am looking to change the image dis ...

Next.js server-side rendering encountered an issue with hydration

I'm currently facing issues while using the react-i18next dependency with next.js. Within my _app.js file, I have the following code snippet: if (!isServer) { init_i18n(); } function MyApp({ Component, pageProps }) { // The presence of this ...

Utilize elements within a for loop to iteratively access distinct anchors

Currently, I am working on integrating a blog feature into my Vue project. <li v-for='blog in blogs' :key="blog.id"> <a>{{ blog.name }}</a> </li> I'm looking for a way to add a unique anchor link (to e ...

Tips for including items in a list nested within a dictionary using JavaScript

I'm currently working with a JavaScript dictionary and I need to insert an element into a list that belongs to a specific key within the dictionary. Check out the code snippet below: lines = [ [1,2], [2,4], [2,3], [3,5] ]; nodes = [ ...

Java program that selects elements within a specified range from an array and stores them in a new array

Hello everyone, this is my first time posting here and I'll do my best to be clear in my inquiry. So, the problem I need to tackle for an assignment involves creating an array and writing a program in JAVA that selects elements within the range of -2. ...

Utilizing a separator to individually display each item within a string

How can I print out each element of a string separately without including the last element? var animals = "bear, lion, tiger, jaguar"; $.each(animals.split(",").slice(0,-1), function(index, item) { console.log(item); }); p.s. I want to a ...

What is the best way to delete a document from an array?

After inserting a document with the given structure, I am attempting to modify the array by removing an object that matches specific criteria. In this case, I aim to remove the object with a particular id. The current approach I have taken has not been su ...

Implement Conditional Enabling of Forms in JavaScript or jQuery to Support Single Form Usage

I currently have four forms labeled as form-1, form-2, form-3, and form-4, along with three buttons named Button-1, Button-2, and Button-3. Upon loading the first JSP page, it displays form elements on the screen. My query pertains to clicking on button- ...

Struggling with the challenge of storing data in a factory and efficiently utilizing it across various controllers

As a newcomer to Angular, I have been using it for the past two months and now faced with the task of migrating from AngularJS to Angular in my project. The previous developer heavily relied on $rootScopes to store values across controllers, but I am optin ...

Re-calculating with Jquery when input is updated

I am looking for guidance on how to make the calculator recalculate based on a change in the #calcTotal input field. I have successfully calculated all fields and managed to update the #cwac field when one of the values before it changes. Here is the HTML ...

Guide to displaying PHP output in a format suitable for plotting

I'm currently working on plotting PHP output from a MySQL database using . The desired format for the output should look like this - var data = [ { x: ['giraffes', 'orangutans', 'monkeys'], y: [20, 14, 23], ...

Creating a dynamic header in a Bootstrap4 datatable with scroll search and pagination functionality

I've been attempting to create a Datatable using JSON Data with a dynamic header instead of a static one, but I haven't had much success. I want to display the table within a div element only, rather than using the traditional table tag, as it lo ...

Removing a cookie in Javascript - step by step guide

Cookie Conundrum: I've encountered a curious scenario involving browser cookies. After entering an invalid login ID, an unauthorized cookie appears on my HTML page. Despite my attempts to display and expire the cookie, it stubbornly remains persistent ...