Guide to using Javascript to dynamically insert items into the shopping cart menu list

Greetings! I am diving into the world of JavaScript and currently facing a challenge while working on my eCommerce website project to enhance my web development skills. My query pertains to creating a dynamic system where, upon a user adding items to their cart and opening the shopping cart modal, a GET request utilizing the fetch method communicates with my server. This request retrieves data from my server's API which can then be used to populate a Bootstrap 4 list in real-time. While I have successfully set up the API and server endpoints for data retrieval, I am struggling with implementing the functionality to dynamically showcase the user's cart items within the shopping cart modal and enable each element to be clickable. Additionally, I aim to incorporate product IDs obtained from my API responses. Any code snippets or examples would greatly aid me in this endeavor.

Below is the HTML markup defining the structure of the shopping cart sidebar modal:

<!-- Shopping Cart -->
<div class="modal fixed-right fade" id="modalShoppingCart" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-vertical" role="document" >

      <!-- Full cart (add `.d-none` to disable it) -->
      <div class="modal-content">

        <!-- Close -->
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <i class="fe fe-x" aria-hidden="true"></i>
        </button>

        <!-- Header-->
        <div class="modal-header line-height-fixed font-size-lg">
          <strong class="mx-auto">Your Cart (2)</strong>
        </div>

        <!-- List of products in cart 1 -->
        <ul class="list-group list-group-lg list-group-flush">
          <li class="list-group-item">
            <div class="row align-items-center">
              <div class="col-4">

                <!-- Image -->
                <a href="./product.html">
                  <img class="img-fluid" src="/static/assets/img/products/product-6.jpg" alt="...">
                </a>

...

Given the visual representation of the shopping cart that appears when clicked, as seen here: [Image Link], how can I leverage JavaScript to dynamically populate this list with numerous items retrieved from my database, maintaining the existing structure?

For reference, the following outlines the data structure representing a user's cart utilized within my API:

{  
 "session": "test-session",
 "cart total": 2,
  "products": [{
            "product_id": 1,
             "name": "product 1",
              "price": "$20",
               "image": "example.com/pics/product1.jpg"},
                   {
            "product_id": 2,
             "name": "product 2",
              "price": "$30",
               "image": "example.com/pics/product3.jpg"},
                     {
            "product_id": 3,
             "name": "product 3",
              "price": "$50",
               "image": "example.com/pics/product3.jpg"}]

Answer №1

Here are the essential steps to achieve this functionality. Assuming you are using async await to make sure the data is available before updating the DOM.

I've implemented a list where clicking on an item will display the product_id of that item.

By looping through the products in the data using a simple for loop, I create a new li element for each product.

Each li element is assigned a data attribute called product_id for easy reference when clicked. You can inspect these data attributes by examining the created li elements.

An event listener is attached to each li element during the loop. When clicked, it alerts the product_id associated with that item. This allows you to easily manipulate or update your data based on the selected product_id.

const listEl = document.getElementById('js-list');
const yourData = {
  products: [{
    product_id: 1,
    price: '$20',
  },
  {
    product_id: 2,
    price: '$25',
  },
  {
    product_id: 3,
    price: '$30',
  },
}};

// Loop through the products object using a simple for loop
for (let i = 0; i < yourData.products.length; i++) {
  // Create a new li element
  const el = document.createElement("li");
  // Assign the product_id as a data attribute
  el.setAttribute('product-id', yourData.products[i].product_id);
  // Add event listeners
  el.addEventListener('click', () => {
    // Retrieve the product_id from the dataset
    const itemClicked = el.getAttribute('product-id');
    alert('You clicked on product ' + itemClicked);
  });
  // Set the content of the li element
  el.textContent = yourData.products[i].price;
  // Append the li element to the list
  listEl.appendChild(el);
}
<ul id="js-list"></ul>

This should help you get started in the right direction.

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

Issue with Jquery modal not functioning properly on second attempt

Currently, I am working on developing an application using CodeIgniter. However, I have encountered a problem where the modal window does not open for the second time. Here is a more detailed explanation of the issue: The form (view) in question contains ...

Vuex was unable to locate the required dependency

Currently, I'm following an instructional video that incorporates Vuex. As shown in my package.json dependencies, I have installed Vuex: { "name": "blabla", "version": "1.0.0", "description": "blablaa", "author": "blabla", "private": true, ...

`How can I activate a modal window when an option is chosen?`

Utilize the select tag and modal window tag for this example. <select id="selectBox"> <option value="0">Select</option> <option value="1">Yes</option> <option value="2">No</option> </select> <div id ...

Using Typescript in NextJS 13 application router, implement asynchronous fetching with async/await

Recently, I implemented a fetch feature using TypeScript for my NextJS 13 project. As I am still getting familiar with TypeScript, I wanted to double-check if my approach is correct and if there are any potential oversights. Here is the code snippet from ...

Validating fields using JavaScript and HTML

I'm having an issue with the code below because it only allows me to log in with the user and password from the last position of the arrays. I want it to let me login with each user and their corresponding password, for example, user at position 1 wit ...

Issue with Bootstrap Grid functionality

I've been working solo on a project and it's been smooth sailing so far. However, after making some changes to my code, the grids are not displaying as desired. Instead of three columns, only one is showing up and I can't seem to pinpoint th ...

What is the best way to stop an embedded mp4 video from playing when a dynamically generated button is clicked?

After making modifications to the QuickQuiz code found at https://github.com/UrbanInstitute/quick-quiz, I have replaced the img with an embedded mp4 video that loads from a JSON file. Additionally, I switched from using the original SweetAlert library to S ...

Issues with the initial calculator project I built using JavaScript (excluding HTML and CSS)

My first calculator is nearly complete, but I have encountered a challenge. The functionality of my calculator is quite simple; it prompts the user for input using window.prompt and performs addition, subtraction, multiplication, or division based on the u ...

How is the script type "text/html" utilized in contemporary applications? Is this specific example regarded as effective usage?

Is it considered good practice in today's standards to utilize something like the following code snippet and use jQuery to swap out content based on a selector? <script type="text/html" id="this-content1"> <h1>This Header Info One</h1& ...

There was an error in the syntax: a semicolon is missing before the statement

During an ajax request, I encountered this error and upon reviewing it thoroughly, I am unable to pinpoint the cause. The following code snippet is where the issue seems to lie: $('#post_submit').click(function() { var poster_id = <?php echo ...

Inserting a vertical barrier in the midst of the content

I am struggling to create a vertical divider and align the text properly in the top right corner of my screen. https://i.sstatic.net/UqURE.png Currently, I am facing issues with displaying the divider and positioning the text correctly. <div class="r ...

Goodbye.js reliance on lodash

In my search for the most lightweight and speedy jQuery implementation for server-side NodeJs, I've come across Cheerio as the best option. However, I've noticed that Cheerio has a code-size of around 2.6 MB, with approximately 1.4 MB attributed ...

Transforming a JSON into a JavaScript object using deserialization

Within a Java server application, there exists a string that can be accessed through AJAX. The structure of this string is exemplified below: var json = [{ "adjacencies": [ { "nodeTo": "graphnode2", "nodeFrom": "graphnode1" ...

Does the onchange function in the dropdown list only work when the first item is changed?

Here is a snippet of my HTML code featuring a list item generated from a database using a foreach loop: <select class="form-control select" id="inventoryitem" name="inventoryitem" onchange="getunit();"> <option>---Select an item---</o ...

What is the reason for not being able to utilize the same ID more than once?

This snippet of code may not be complete, but it effectively addresses the issue at hand. <body onload="init()"> <nav> <h1 style="font-family:Helvetica;"> <ul class="nav"> <li ><a href="#">Me ...

React is unable to identify the property that was passed to a styled-component in Material UI

Custom Styled Component Using Material-UI: import { Typography } from '@material-ui/core'; const CustomText = styled(Typography)<TextProps>` margin-bottom: 10px; color: ${({ textColor }) => textColor ?? textColor}; font-size: ${( ...

What is the best way to clear h:messages within an ace:dialog following an ajax operation?

I have implemented a button (Activate Popup) that displays a pop-up. After submitting the form, an error message may appear in the h:messages field as intended. My issue arises when I close the pop-up (Deactivate Popup) and reopen it (Activate Popup), the ...

The property of undefined map cannot be read

import React from 'react'; import { Card, Text } from "react-native-paper"; import { SafeAreaView, } from "react-native"; class HackerNewsClone extends React.Component { constructor(props) { super(props); this.sta ...

Assign a custom value to the ng-options and ensure that the first option is selected by default

Hey there, I'm currently working on the following: $scope.test = [ {"value" : 0, "text" : "00:00"}, {"value" : 900, "text" : "00:15"}, {"value" : 1800, "text" : "00:30"} ]; and in my select element, this is what I hav ...

Building interactive forms in Angular 6

I want to design a dynamic form that creates a new form when the AddNew button is clicked. In my TypeScript (ts) file, I have the following code: addinfoForm: FormGroup; infoNameList: FormArray; infoModel: Productdetail; constructor(private fb ...