Iterate over the items stored in localStorage and display a particular value when clicked

For my library project, I am trying to create a shopping cart feature. The issue I'm facing is that when I click on a specific book, I cannot add it to another localStorage.

This is my html    <!--Knjige-->
<div class="container grid" id='knjige'></div>

This is my CSS:

.container{
    margin: 50px;   }

  .grid{
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    grid-gap: 20px;
    align-items: start;   }

  .grid-card{
    border: 1px solid #ccc;
    box-shadow: 2px 2px 6px 0px  rgba(0,0,0,0.3);
    background: orange;
    z-index: 9;   }

  .text:hover{
    color: #fff;
    cursor: pointer;   }

  .text{
    padding: 0 20px 20px;
    color: black;
    font-weight: bold;   }

And this is my JavaScript, please note that I'm not allowed to use jQuery

let knjige = [

    {"Naziv":"4_50 From Paddington_ A Miss Marple Mystery",
    "ID":"XA7JORPL",
    "Autor":"Agatha Christie",
    "Godina":"2007",
    "Cena":546,
    "Raspolozivo_stanje":50,
    },

    {"Naziv":"Lord Edgware Dies (1986, Berkley)",
    "ID":"BPL6QUG5",
    "Autor":"Agatha Christie",
    "Godina":"1986",
    "Cena":1041.06,
    "Raspolozivo_stanje":15,
    },

    {"Naziv":"Murder at the Vicarage  (2000, Signet)",
    "ID":"T2CGKTQQ",
    "Autor":"Agatha Christie",
    "Godina":"2000",
    "Cena":546,
    "Raspolozivo_stanje":44,
    },

    {"Naziv":"Sparkling Cyanide (1989)",
    "ID":"1QIFZZ4P",
    "Autor":"Agatha Christie",
    "Godina":"1989",
    "Cena":1114.91,
    "Raspolozivo_stanje":45,
    },

    {"Naziv":"The Mystery of the Blue Train",
    "ID":"4C4XW7H2",
    "Autor":"Agatha Christie",
    "Godina":"1928",
    "Cena":1041.06,
    "Raspolozivo_stanje":"",
    }
    ];

    if(!localStorage.getItem('knjige')){
        window.localStorage.setItem('knjige', JSON.stringify(knjige));
    }

    let knjigeLocalStorage = JSON.parse(window.localStorage.getItem('knjige'));

    window.onload = function(show){
        for(knjiga of knjigeLocalStorage){
            show += `
                <div class='grid-card'>
                    <div class='text'>
                        <h4>Title: ${knjiga.Naziv}</h4>
                        <p>Author: ${knjiga.Autor}</p>
                        <p>ID: ${knjiga.ID}</p>
                        <p>Year: ${knjiga.Godina}</p>
                        <p>Price: ${knjiga.Cena}</p>
                        <p>Available Quantity: ${knjiga.Raspolozivo_stanje}</p>
                        <button class='btn' id='dugme' onclick=''><i class="fas fa-shopping-cart"></i></button>
                    </div>
                </div>
            `;
        };
        document.getElementById('knjige').innerHTML = show;
    };

I want to display the value of the specific book when the button is clicked. Hope I explained it clearly..

Thanks!

Answer №1

  1. You need to correct a value here:
    for(knjiga of knjigeLocalStorage){
  2. Using innerHTML can cause issues with onclick events and HTML rendering.

I personally prefer using addEventListener and adding elements through the DOM. It may be considered old-fashioned, but it works well.

document.addEventListener("DOMContentLoaded", (event) => {
    const div = document.getElementById('knjige');

    knjigeLocalStorage.forEach((k) => {

    const d = document.createElement("div");
    d.classList.add("grid-card");
    const text = document.createElement("div");
    text.classList.add("text");
    const h4 = document.createElement("h4");
    h4.innerHTML = `Naziv ${k.Naziv}`;
    const button = document.createElement("button");
    const i = document.createElement("i");
    i.classList.add("fas", "fa-shopping-cart");
    button.appendChild(i);

    button.addEventListener("click", () => {

        alert(`Naziv ${k.Naziv}`);

    });


    text.append(h4);
    text.append(button);
    d.appendChild(text);
    div.appendChild(d);
  });

}); 

Give this fiddle a try:

https://jsfiddle.net/2cor9v1w/

document.addEventListener("DOMContentLoaded") Does not work as expected with JSFiddle, so you might need it in your actual code instead of window.onload.

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

Utilizing a Struct-based Array in a Function to Populate Array with Data from a File

Currently working on a structs lab assignment, I am tasked with reading statistics about 10 different dinosaurs from a text file and storing that information into a struct. Despite having error-free code, the console output remains blank. It seems that I a ...

Is it possible to use the ""get" prefix for a function in Spring Boot?

I am facing an issue with my Mcq class that is linked to a MongoRepository. I am trying to retrieve an instance of my Mcq after applying certain changes such as shuffling answers and drawing questions. I have defined a function called "myMcq.getInstance()" ...

Ways to retrieve the pending count of XMLHttpRequests in JavaScript

I am trying to figure out how to capture the count of pending xmlhttprequests in a web page using javascript while working with selenium and python. It seems like there is a useful link that could help me get this information, but I'm having trouble ...

When a string begins with the "<" character, jQuery regex is unable to find a match

I am attempting to check if a string starts with the "<" character, but I am running into issues. The expression works perfectly fine on regex101.com, however, it fails when used in my personal files. When I input a backslash everything works as expect ...

Can regex matching characters be made easier to understand?

I am working on creating an ECMAScript (JavaScript) flavored regex to evaluate the complexity of my password based on specific criteria: Characters Used Password Strength Length ABC abc 123 #$& WEAK ... 1 x ...

I am in the process of transforming my basic JS Array into one that contains key/value

Currently, I am utilizing jQuery to create an Array in the following manner: var arr = new Array(); $('#some-form .some-input').each(function() { arr.push($(this).val()); ...

Using Stringify to modify the value of a particular array in Local Storage

Uncertain of the accuracy of my question, but I am attempting to modify a value within a localstorage array. This is what my localstorage currently contains: [{"id":"item-1","href":"google.com","icon":"google.com"}, {"id":"item-2","href":"youtube.com","i ...

Remove a div element with Javascript when a button is clicked

I am working on a project where I need to dynamically add and remove divs from a webpage. These divs contain inner divs, and while the functionality to add new divs is working fine for me, I'm facing some issues with removing them. The code snippet b ...

Troubleshoot: React and Laravel login authentication issues

I am relatively new to working with React, React Router, and Laravel for authentication. I've been trying to set up authentication using Laravel, React, and React Router, and although the page redirects to the desired destination when the submit butto ...

Sending an array of objects to a MySQL database using React and NodeJS: A comprehensive guide

As someone who is new to NodeJS and Mysql databases, I am currently working on a small React project that involves a week calendar for booking lessons. My main focus right now is creating an admin panel where teachers can set their availability throughout ...

Is the dataType: "json" parameter necessary in AJAX requests under certain conditions?

Upon observation, it appears that there is no need to include dataType: "json" in our AJAX request when the server file is already structured in .json format. index.html $.ajax({ url: "ajax/test.json", data: "id="+id, cache: false, type: ...

An issue occurred while deploying Docker on Railway services: Build Error

After successfully deploying my Django project on Railway, I decided to add SendGrid mail functionality using the django-sendgrid-v5 package. Everything worked fine in the development environment, including sending emails like user signups. However, when ...

Bringing joy to a JS library: Embracing both Node and the Window

I have developed a JS library that I want to convert into a Node module for use with Node.js. This library extends the Canvas context API and relies on the use of getImageData(). Therefore, it begins with a defensive check to ensure compatibility: if (wi ...

Issue with alert not appearing after webpage is refreshed or reloaded on Angular v10

I'm currently working on an Angular single page application. When a user clicks a button, the page refreshes and a message is supposed to be displayed. (TYPESCRIPT) import { Component, OnInit, OnDestroy } from '@angular/core'; export class ...

Should I package my dependencies with webpack for production builds?

As I utilize webpack to generate my production bundle for my express application, I had high hopes for the externals field. I believed that it would package up all the required dependencies for deployment without the need for a yarn install or npm install. ...

Guide on incorporating an Ajax spinner to a Slideshow

I am in need of assistance with creating a manual slideshow that includes an ajax loader image. The goal is to display the loader image every time I click on the Previous or Next buttons, until the Test 1, Test 2, and Test 3 texts are fully loaded. Any sug ...

Is there a way to specifically execute a Mongoose validate function solely for the create user page and not the edit user page?

Exploring Different Tools In the process of developing a website using Node.js, Express, and MongoDB. Leveraging mongoose for interacting with the MongoDB server has been quite beneficial. However, I encountered an issue where a function within my Mongo ...

Using PHP to identify a unique pattern within a hostname

I need to extract specific hostnames matching a certain pattern from a list of provided hostnames. Given Hostnames: sub1.hostname1.com sub12.hostname2.com suboo2.hostname3.com sub2.hostname4.com Expected Output after filtering with preg_match: sub1.hos ...

Is it possible to utilize custom CSS to conceal commas and evade a JSX bug?

One element of my website relies on the following .js code snippet: items.add( `field-${field.id()}`, <div className="Mason-Field Form-group"> <label> {field.icon() ? <>{icon(field.icon())} & ...

Enhancing Struts2 JSON Plugin: Including ActionMessages, ActionErrors, and FieldErrors in the response

While working on my jQuery Ajax posts, I want to include any actionmessages, actionerrors, and fielderrors in the response (in JSON format). Here is what I added: <result name="input" type="json"> <param name="ignoreHierarchy">false&l ...