Search code examples
javascriptlocal-storageinnerhtml

How do I add an additional item to my cart?


with my current code, I have my added items which are in my localstorage, but it only shows me one in my basket

and I don't see how to solve my problem, do you have any idea?

function displayPanier(product) {
  
   function getTeddies() {
    let teddiesPanier = JSON.parse(localStorage.getItem("basketProducts"));
    return teddiesPanier; 
   }
   
   
   let teddiesPanier = getTeddies();

   //faire une boucle pour iterrer sur les produits dans le local storage

   function panierTeddies (){
     
   
       const panierStorage = document.getElementById("test")
       panierStorage.innerHTML = `
       <table class="table bg-light">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">Photo</th>
            <th scope="col">Nom</th>
            <th scope="col">Prix</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <th scope="row">1</th>
            <td><img id=panierImg class="img-fluid" src="${teddiesPanier[0].imageUrl}"  style="max-width: 40px;"></td>
            <td><h5 class="font card-title">${teddiesPanier[0].name}</h5></td>
            <td><p class="card-text prix">${teddiesPanier[0].price / 100}€</p></td>
          </tr>
        </tbody>
      </table>
      <td><button onclick="removeProduct('${product}')" class="btn btn-primary">Supprimer</button></td>

   `
   }
   console.table(teddiesPanier)
   panierTeddies();
}

screenshhot basket with localstroage in console


Solution

  • It only shows (1) item because you didn't iterate over the array of items from your localStorage. e.g. ${teddiesPanier[0].name}.

    What you can do is modify the code into this:

      panierStorage.innerHTML = `
           <table class="table bg-light">
            <thead>
              <tr>
                <th scope="col">#</th>
                <th scope="col">Photo</th>
                <th scope="col">Nom</th>
                <th scope="col">Prix</th>
              </tr>
            </thead>
            <tbody>`;
    
          for (var i=1; i < teddiesPanier.length; i++) {
    panierStorage.innerHTML += `
                <tr>
                  <th scope="row">${i}</th>
                  <td><img id=panierImg class="img-fluid" src="${teddiesPanier[i].imageUrl}"  style="max-width: 40px;"></td>
                  <td><h5 class="font card-title">${teddiesPanier[i].name}</h5></td>
                  <td><p class="card-text prix">${teddiesPanier[i].price / 100}€</p></td>
                </tr>
                `;
          }
    
    panierStorage.innerHTML += `<td><button onclick="removeProduct('${product}')" class="btn btn-primary">Supprimer</button></td></tbody>
          </table>`;