Home > database >  What is the error in the input card codes
What is the error in the input card codes

Time:07-18

What is the error in the input card codes, the - buttons work fine, but the value of the input is not added to the basket with the product, only one product is added ..........................................................................................................................................................................................................

  var shoppingCart = (function() {
   
   // =============================
   // Private methods and propeties
   // =============================
   cart = [];
   // Constructor
   function Item( name, price, count, image) {
     this.name = name;
     this.price = price;
     this.count= count;
     this.image = image
   }
   
   // Save cart
   function saveCart() {
     localStorage.setItem('shoppingCart', JSON.stringify(cart));
   }
   
     // Load cart
   function loadCart() {
     cart = JSON.parse(localStorage.getItem('shoppingCart'));
   }
   if (localStorage.getItem("shoppingCart") != null) {
     loadCart();
   }
   
  
   // =============================
   // Public methods and propeties
   // =============================
   var obj = {};
   
   // Add to cart
   obj.addItemToCart = function(name, price, count, image) {
     for(var item in cart) {
       if(cart[item].name === name) {
         cart[item].count   ;
         saveCart();
         return;
       }
     }
     var item = new Item(name, price, count, image);
     cart.push(item);
     saveCart();
   }
   // Set count from item
   obj.setCountForItem = function(name, count) {
     for(var i in cart) {
       if (cart[i].name === name) {
         cart[i].count = count;
         break;
       }
     }
   };
   // Remove item from cart
   obj.removeItemFromCart = function(name) {
       for(var item in cart) {
         if(cart[item].name === name) {
           cart[item].count --;
           if(cart[item].count === 0) {
             cart.splice(item, 1);
           }
           break;
         }
     }
     saveCart();
   }
  
   // Remove all items from cart
   obj.removeItemFromCartAll = function(name) {
     for(var item in cart) {
       if(cart[item].name === name) {
         cart.splice(item, 1);
         break;
       }
     }
     saveCart();
   }
  
   // Clear cart
   obj.clearCart = function() {
     cart = [];
     saveCart();
   }
  
   // Count cart 
   obj.totalCount = function() {
     var totalCount = 0;
     for(var item in cart) {
       totalCount  = cart[item].count;
     }
     return totalCount;
   }
  
   // Total cart
   obj.totalCart = function() {
     var totalCart = 0;
     for(var item in cart) {
       totalCart  = cart[item].price * cart[item].count;
     }
     return Number(totalCart.toFixed(2));
   }
  
   // List cart
   obj.listCart = function() {
     var cartCopy = [];
     for(i in cart) {
       item = cart[i];
       itemCopy = {};
       for(p in item) {
         itemCopy[p] = item[p];
  
       }
       itemCopy.total = Number(item.price * item.count).toFixed(2);
       cartCopy.push(itemCopy)
     }
     return cartCopy;
   }
  
   // cart : Array
   // Item : Object/Class
   // addItemToCart : Function
   // removeItemFromCart : Function
   // removeItemFromCartAll : Function
   // clearCart : Function
   // countCart : Function
   // totalCart : Function
   // listCart : Function
   // saveCart : Function
   // loadCart : Function
   return obj;
  })();
  
  
  // *****************************************
  // Triggers / Events
  // ***************************************** 
  // Add item
  $('.additem').click(function(event) {
   event.preventDefault();
   var name = $(this).data('name');
   var price = parseInt($(this).data('price'));
   var image  = $(this).parents("div.card").find(".card-img-top").attr('src')
   shoppingCart.addItemToCart(name, price, 1 ,image);
   displayCart();
  });
  
  // Clear items
  $('.clear-cart-items').click(function() {
   shoppingCart.clearCart();
   displayCart();
  });
  
  
  function displayCart() {
  
   var cartArray = shoppingCart.listCart();
   var output = "";
   for(var i in cartArray) {
        output  = "<tr class='cartTable'>"
          "<td><img src='"   cartArray[i].image   "' style='width:150px;'></td>" 
         "<td class='TableTitle'>"   cartArray[i].name   "</td>"
         "<td>"   cartArray[i].price   "</td>"
         "<td><div class='input-group'><button class='minus-item input-group-addon btn btn-primary' data-name="   cartArray[i].name   ">-</button>"
         "<input type='number' class='item-count form-control' data-name='"   cartArray[i].name   "' value='"   cartArray[i].count   "'>"
         "<button class='plus-item btn btn-primary input-group-addon' data-name="   cartArray[i].name   "> </button></div></td>"
         "<td><button class='delete-item btn btn-danger' data-name="   cartArray[i].name   ">X</button></td>"
         " = " 
         "<td>"   cartArray[i].total   "</td>" 
          "</tr>"; 
       
   }
   $('.show-cart').html(output);
   $('.total-cart').html(shoppingCart.totalCart());
   $('.total-count').html(shoppingCart.totalCount());
  }
  
  
  // Delete item button
  
  $('.show-cart').on("click", ".delete-item", function(event) {
   var name = $(this).data('name')
   shoppingCart.removeItemFromCartAll(name);
   displayCart();
  })
   
   //These are the codes of the internal input, the input of the cart
   //This input works well and the buttons are as well. When you 
  click 
   on each button, the value is provided
  // -1
  $('.show-cart').on("click", ".minus-item", function (event) {
   var name = $(this).data('name')
   shoppingCart.removeItemFromCart(name);
   displayCart();
  })
  
  
  //  1
  $('.show-cart').on("click", ".plus-item", function(event) {
   var name = $(this).data('name')
   shoppingCart.addItemToCart(name);
   displayCart();
  })
  
  
  // Item count input
  $('.show-cart').on("change", ".item-count", function(event) {
    var name = $(this).data('name');
    var count = Number($(this).val());
   shoppingCart.setCountForItem(name, count);
   displayCart();
  });
  
  
  displayCart();
  
  
//These are the codes of the external input, the input of the card
//here the buttons   - work fine but the input value is not added to the cart, only one product is added, even if the input value is 10
  
  function increaseCount(a, b) {
    var input = b.nextElementSibling;
    var value = parseInt(input.value, 10);
    value = isNaN(value) ? 0 : value;
    value  ;
    input.value = value;
    displayCart();
  }
  
  function decreaseCount(a, b) {
    var input = b.previousElementSibling;
    var value = parseInt(input.value, 10);
    if (value > 1) {
      value = isNaN(value) ? 0 : value;
      value--;
      input.value = value;
    }
  }
<div >


  <div  >
      <img   src="images/img/1.png" alt="Product Name" data-hook="product-image">
     <div >
       <div >
          <span >Offer</span><span >1.50</span>
       </div>
     </div>
      <div >
          <span>Germany</span>
          <h2   >Product 1</h2>
           <span>weight</span>
           <span>tax</span>
      </div>
      <fieldset   data-hook="product-item-quantity-counter" 
      aria-label="select quantity" dir="rtl" data-error="false">

     <div>
       <button   data-name=`cartArray[i].name`  onClick='increaseCount(event, this)' ><span  data-name="cartArray[i].name" >
           add
           </span></button>

           <input type="number"    value="1"   data-name="cartArray[i].name"  min="1" max="20" step="1" >

           <button   data-name="cartArray[i].name" onClick='decreaseCount(event, this)'  value="1" ><span data-name="cartArray[i].name" >
               remove
               </span></button>
     </div>
      </fieldset>
      <button   data-name="Product"  data-price="2.00 '€'" onclick="addNew()"> 
       <label >Add Item</label> <span >
          shopping_cart</span>
          <span >shopping_cart</span>
          <i  aria-hidden="true"  style="font-size: 15px;"></i>      
        </button>
  </div>
</div>

CodePudding user response:

ok so I fixed the issue, I also changed all vars to let or const to ensure data values don't get manipulated. You just needed to pass the count though to the add basket method

    let count = parseInt($(this).parents("div.card").find(".item-count").val());
    shoppingCart.addItemToCart(name, price, count, image);

then in the basket method needed to either use the passed-in value or add 1 to the count for the icon when the item is in the basket

cart[item].count  = count ||  1

I fixed a few other minor things too

see: https://jsfiddle.net/PatrickHume/h7wabuLr/ (the below won't run because SO doesn't allow localStorage in their code runners

const shoppingCart = (function() {

  // =============================
  // Private methods and properties
  // =============================
  let cart = [];
  // Constructor
  class Item {
    constructor(name, price, count, image) {
      this.name = name;
      this.price = price;
      this.count = count;
      this.image = image;
    }
  }

  // Save cart
  function saveCart() {
    localStorage.setItem('shoppingCart', JSON.stringify(cart));
  }

  // Load cart
  function loadCart() {
     cart = JSON.parse(localStorage.getItem('shoppingCart'));
  }
  if (localStorage.getItem("shoppingCart") != null) {
    loadCart();
  }


  // =============================
  // Public methods and properties
  // =============================
  const obj = {};

  // Add to cart
  obj.addItemToCart = function(name, price, count, image) {
  debugger
    for (let item in cart) {
      if (cart[item].name === name) {
        cart[item].count  = count ||  1
        saveCart();
        return;
      }
    }
    let item = new Item(name, price, count, image);
    cart.push(item);
    saveCart();
  }
  // Set count from item
  obj.setCountForItem = function(name, count) {
    for (let i in cart) {
      if (cart[i].name === name) {
        cart[i].count = count;
        break;
      }
    }
  };
  // Remove item from cart
  obj.removeItemFromCart = function(name) {
    for (let item in cart) {
      if (cart[item].name === name) {
        cart[item].count--;
        if (cart[item].count === 0) {
          cart.splice(item, 1);
        }
        break;
      }
    }
    saveCart();
  }

  // Remove all items from cart
  obj.removeItemFromCartAll = function(name) {
    for (let item in cart) {
      if (cart[item].name === name) {
        cart.splice(item, 1);
        break;
      }
    }
    saveCart();
  }

  // Clear cart
  obj.clearCart = function() {
    cart = [];
    saveCart();
  }

  // Count cart 
  obj.totalCount = function() {
    let totalCount = 0;
    for (let item in cart) {
      totalCount  = cart[item].count;
    }
    return totalCount;
  }

  // Total cart
  obj.totalCart = function() {
    let totalCart = 0;
    for (let item in cart) {
      totalCart  = cart[item].price * cart[item].count;
    }
    return Number(totalCart.toFixed(2));
  }

  // List cart
  obj.listCart = function() {
    let cartCopy = [];
    for (let i in cart) {
      let item = cart[i];
      itemCopy = {};
      for (let p in item) {
        itemCopy[p] = item[p];
      }
      itemCopy.total = Number(item.price * item.count).toFixed(2);
      cartCopy.push(itemCopy)
    }
    return cartCopy;
  }

  // cart : Array
  // Item : Object/Class
  // addItemToCart : Function
  // removeItemFromCart : Function
  // removeItemFromCartAll : Function
  // clearCart : Function
  // countCart : Function
  // totalCart : Function
  // listCart : Function
  // saveCart : Function
  // loadCart : Function
  return obj;
})();


// *****************************************
// Triggers / Events
// ***************************************** 
// Add item
$('.additem').click(function(event) {
  event.preventDefault();
  let name = $(this).data('name');
  let price = parseInt($(this).data('price'));
  let image = $(this).parents("div.card").find(".card-img-top").attr('src')
  let count = parseInt($(this).parents("div.card").find(".item-count").val());
  shoppingCart.addItemToCart(name, price, count, image);
  displayCart();
});

// Clear items
$('.clear-cart-items').click(function() {
  shoppingCart.clearCart();
  displayCart();
});


function displayCart() {
  let cartArray = shoppingCart.listCart();
  let output = "";
  for (let i in cartArray) {
    output  = "<tr class='cartTable'>"  
      "<td><img src='"   cartArray[i].image   "' style='width:150px;'></td>"  
      "<td class='TableTitle'>"   cartArray[i].name   "</td>"  
      "<td>"   cartArray[i].price   "</td>"  
      "<td><div class='input-group'><button class='minus-item input-group-addon btn btn-primary' data-name='"   cartArray[i].name   "'>-</button>"  
      "<input type='number' class='item-count form-control' data-name='"   cartArray[i].name   "' value='"   cartArray[i].count   "'>"  
      "<button class='plus-item btn btn-primary input-group-addon' data-name='"   cartArray[i].name   "'> </button></div></td>"  
      "<td><button class='delete-item btn btn-danger' data-name='"   cartArray[i].name   "'>X</button></td>"  
      " = "  
      "<td>"   cartArray[i].total   "</td>"  
      "</tr>";

  }
  $('.show-cart').html(output);
  $('.total-cart').html(shoppingCart.totalCart());
  $('.total-count').html(shoppingCart.totalCount());
}


// Delete item button

$('.show-cart').on("click", ".delete-item", function(event) {
  let name = $(this).data('name')
  shoppingCart.removeItemFromCartAll(name);
  displayCart();
})

//These are the codes of the internal input, the input of the cart
//This input works well and the buttons are as well. When you 
//click 
// each button, the value is provided
// -1
$('.show-cart').on("click", ".minus-item", function(event) {
  let name = $(this).data('name')
  shoppingCart.removeItemFromCart(name);
  displayCart();
})


//  1
$('.show-cart').on("click", ".plus-item", function(event) {
debugger;
  let name = $(this).data('name')
  shoppingCart.addItemToCart(name);
  displayCart();
})


// Item count input
$('.show-cart').on("change", ".item-count", function(event) {
  let name = $(this).data('name');
  let count = Number($(this).val());
  shoppingCart.setCountForItem(name, count);
  displayCart();
});


displayCart();


//These are the codes of the external input, the input of the card
//here the buttons   - work fine but the input value is not added to the cart, only one product is added, even if the input value is 10

function increaseCount(a, b) {
  let input = b.nextElementSibling;
  let value = parseInt(input.value, 10);
  value = isNaN(value) ? 0 : value;
  value  ;
  input.value = value;
  displayCart();
}

function decreaseCount(a, b) {
  debugger;
  let input = b.previousElementSibling;
  let value = parseInt(input.value, 10);
  if (value > 1) {
    value = isNaN(value) ? 0 : value;
    value--;
    input.value = value;
  }
}
<div >
  <div >
    <img  width="50px" height="50px" src="https://pngpress.com/wp-content/uploads/2020/08/uploads_guava_guava_PNG60.png" alt="product-img" data-hook="product-image">
    <div >
      <div >
        <span >Offer</span><span >1.50</span>
      </div>
    </div>
    <div >
      <span>Germany</span>
      <h2 >Product-name</h2>
      <span>weight</span>
      <span>tax</span>
    </div>
    <fieldset  data-hook="product-item-quantity-counter" aria-label="select the quantity" dir="rtl" data-error="false">

      <div>
        <button  data-name=`cartArray[i].name` onClick='increaseCount(event, this)'><span data-name="cartArray[i].name" >
            add
          </span></button>

        <input type="number"  value="1" data-name="cartArray[i].name" min="1" max="20" step="1">

        <button  data-name="cartArray[i].name" onClick='decreaseCount(event, this)' value="1"><span data-name="cartArray[i].name" >
            remove
          </span></button>
      </div>
    </fieldset>
    <button  data-name="tne name of the product" data-price="2.00"> Add Item<span >
        shopping_cart
      </span></button>
  </div>

</div>
<table >

</table>
<div>
  <p>
  </p>
  <container>Total amount: <item >0
    </item>
  </container>
  <p></p>
  <container>Number of Items: <item >0
    </item>
  </container>
</div>

I hope this helps

CodePudding user response:

you need to change your code a bit to pass it though, a bit like the following...

function Item( name, price, count, image) {
     this.name = name;
     this.price = price;
     this.count= count;
     this.image = image
   }
obj.addItemToCart = function(name, price, count, image) {
     for(var item in cart) {
       if(cart[item].name === name) {
         cart[item].count   ;
         saveCart();
         return;
       }
     }
     var item = new Item(name, price, count, image);
     cart.push(item);
     saveCart();
   }
$('.additem').click(function(event) {
   event.preventDefault();
   var name = $(this).data('name');
   var price = Number($(this).data('price'));
   var image  = $(this).parents("div.ourproducts").find(".card-img-top").attr('src')
   shoppingCart.addItemToCart(name, price, 1 ,image );
   displayCart();
  });

then just add the image into your displayCart string append

(I have updated the below line )

 "<td><img src='"   cartArray[i].image   "' alt='product-img' data-hook='product-image'></td>"   

I hope this helps

  • Related