Collecting Information from the DOM to Append to an Array with JavaScript

My aim is to create a fully functional shopping cart using either vanilla JavaScript or jQuery. I'm uncertain if I'm approaching it the right way, but here's my plan:

  1. Firstly, I want to establish an array named cartItems to store all shopping cart data such as ID, price, image, description, weight, and tax.

  2. To populate this array, I intend to either add an event listener to the add to cart button or select the button element by ID. I'm unsure about setting up different listeners for multiple products that all need to go through the same process to be added to the cart.

  3. Once the cart data is added to the array, I can then use it to display the Cart page. This page will include options to update the quantity and remove items, with the array being edited to reflect these changes.

The main challenge at the moment is the second part - "waiting" for the add to cart button click and processing the necessary data.


**HTML**

// HTML CODE GOES HERE

**CSS**

// CSS CODE GOES HERE

**JavaScript/jQuery**

let cartItems = [];

function cartProduct(id, product, price, weight, vat) {
  this.id = id;
  this.product = product;
  this.price = price;
  this.weight = weight;
  this.vat = vat;
}

function addToCart() {
  cartItems = JSON.parse(sessionStorage.getItem("cartItems"));
  let newProduct = new cartProduct();
  document.getElementById('atc-button');
}

I acknowledge that my JavaScript file is incomplete and lacks proper structure. I am in the process of learning the best way to approach this task. My goal is to capture the product details and add them to the array when the add to cart button is clicked.

Answer №1

Initially, the catalog could serve as a data repository. To uniquely identify each product, you may consider using a sku rather than an id. With this in mind, you could implement the following logic:

// Converting a NodeList into an actual Array
const addToCartBtns = [...document.querySelectorAll(".atc-button")];

addToCartBtns.forEach(button => {
  /***
   * At this point, the `button` instance is available to manage
   *   its own clicks and updates.
   */
  button.addEventListener("click", function(){
    const productSKU = button.getAttribute('data-product-id');
    // By utilizing the sku/id, we can filter the data store or
    //   fetch the appropriate entry. It's not necessary to add
    //   all data to the cart, just the sku and quantity. Product
    //   and price details are only required for display, already
    //   stored in our data repository!
    cartItems.push({
      sku: productSKU,
      qty: 1 /* initial quantity */
    });
    // At this stage, it would be ideal to inform the user
    //   that the cart has been updated, possibly refresh the
    //   view or redirect them to the cart for quantity
    //   adjustments.
  }); 
});

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

Acquiring the Facebook profile_id and incorporating it into a URL using a Chrome Extension

Although I have limited knowledge of JavaScript, I believe I know enough to complete the task at hand; I just need some guidance. I am working on developing an extension that will extract the profile_id from the current Facebook page being viewed, and the ...

Unable to reach the prototype of the object

I am encountering an issue while attempting to access the object's prototype in a Node.js code. The objective is to send this object through an API so that users can utilize its methods. The problem lies in the fact that the returned object only inclu ...

I want to set a single background image for all slides in fullPage.js. How can I achieve this

I am attempting to replicate a similar effect as shown in this example: The demonstration above utilizes the fullPage.js plugin. You may have noticed how the background image remains consistent while navigating through different sections. I have searched ...

Hiding loading spinner in Ionic 2 upon iframe completion

I need to embed an external webpage in my app using an iframe. I have successfully implemented a loading animation while the iframe is loading, but I am unsure how to hide the animation once the iframe content has loaded. Unfortunately, I am unable to edit ...

Struggling to solve these two CSS Animation issues

I am struggling to replicate a CSS animation similar to this example Currently, I am facing challenges with two specific aspects: #1 - The arrow of my triangle must consistently point towards the circle, but my attempts at rotating it only result in the ...

How can I create space between a checkbox and its label in Google Web Toolkit (GWT)?

How can I create space between a Checkbox and its content in GWT? Checkbox c = new Checkbox("checkme"); c.setStyleName("checkbox_style"); When I try using padding or margin, the entire checkbox and its content move together. Is there a way to achieve a g ...

Customizing the default image of a Select dropdown field in Sencha Touch

Does anyone know how to change the default image of a select dropdown in Sencha Touch to a customized image? I've attached a screenshot for reference but can't seem to find any properties or classes to adjust this. Any guidance would be greatly a ...

The appearance of the mock button varies between the development and production environments due to CSS styling

I'm currently using CSS to style a hyperlink in order to give it the appearance of a button. This is for a .NET website. a.pretend { display:inline-block; border-top:1px solid #CCCCCC; border-left:1px solid #CCCCCC; border-bottom:1px solid #999999; b ...

Trouble encountered while attempting to utilize @click="checkedInput" for displaying checkbox label in Vue.js?

const app = new Vue({ el: '#app', data: { checkedNames: [], checkedName: true, close: false }, methods: { uncheck(checkedName) { this.checkedNames = this.checkedNames.filter(name => name !== checkedName); }, ...

What is the reason objects cannot be compared in JavaScript?

I have a straightforward code snippet here. Its purpose is to authenticate the user against the author of the post and grant the authenticated user access to edit the post. exports.edit = function(req, res){ Post.findById(req.params.post_id, function ...

Unable to retrieve information from localhost site using the expressjs API. I have attempted to use both vue-resource and axios in order to get the data without success

Currently diving into the world of VueJS, I decided to embark on a project. My aim is to retrieve data from an ExpressJS server/API. But unfortunately, both vue-resource and axios have been returning status code 0. It seems like my API might not be handli ...

Is there a way for me to duplicate a complex element multiple times within the same page?

As an illustration, let's say I have a social tab located in my header that I would like to duplicate in the footer. This tab is comprised of various buttons with SVG images on top, event listeners linked to button IDs, and CSS styling. One option is ...

Utilizing JSON and select for dependency management

Let's say we have a JSON object: { "A": { "1": "1", "2": "2", "3": "3" }, "B": { "4": "4", "5": "5", "6": "6" }, "C": { "7": "7", "8": "8" } } And we also have ...

Getting an HTML element by its ID that was passed from the ng-init directive in Angular can be achieved

When I use ng-click, I am able to retrieve the html element by id. However, when I use ng-init, I only get null. Please take a look at my codepen here. HTML Code: <script type="text/javascript"> var memId = "bb7de28f-0f89-4f14-8575-d494203acec7 ...

checkbox-activated navigation bar

Struggling to implement a Nav-drawer that should open when a checkbox is selected, everything seems to be set up correctly but the issue arises when it comes to actually opening it. Here is the code snippet: <div class="leftside"> <input typ ...

What is the best way to enable duplicate entries in ng-repeat?

When utilizing stringify, the json data gets formatted and appears in an alert message. However, when attempting to display it in an actual link, it is not showing up. Upon checking the console, an error was displayed stating that "duplicates are not allow ...

Steps for updating a specific item within an object in an array of MongoDB document

Consider the following data collection, for which I have some questions: { "_id" : ObjectId("4faaba123412d654fe83hg876"), "user_id" : 123456, "total" : 100, "items" : [ { ...

I encountered a problem with the Javascript toggle menu collapsing feature

I have built a custom toggle menu using Javascript: $(document).ready(function() { $('.toggle').click(function () { if ($(this).hasClass("expanded")) { $(this).next().slideUp("fast"); } else { $(&apos ...

Retrieving information from a JSON object in Angular using a specific key

After receiving JSON data from the server, I currently have a variable public checkId: any = 54 How can I extract the data corresponding to ID = 54 from the provided JSON below? I am specifically looking to extract the values associated with KEY 54 " ...

Extract CSS properties to generate a dictionary that maps class names to background images

Suppose my CSS looks like this: .featured .featured_1 { background-image: url("http://test.com/image.png"); margin-top:20px; } In that case, the following PHP function: function extractBackgroundImages($css) { if (!preg_match_all('/&bso ...