javascriptjquery

Can't remove items from the cart correctly (JavaScript & Jquery)


Basically, I have a cart that I recently upgraded to support product customization (at a very basic level). The upgrades included color and material type for a particular bike in addition to name, price, and quantity.

The problem is that since the new features that I added use combo-boxes or options, every time I add items to the cart with slightly different color and material combination if I attempt to delete the previously added combinations, it will only allow me to delete the newest one.

I feel this is easier to show in code than to try and explain it. This is my logic for deleting items off the cart:

//removing one particular item completely from the cart
AS_shoppingCart.removeItemAll = function(name, color, material){
    //for every item in the array which has the same name; remove.
    for (var i in this.cartShop)
        if(this.cartShop[i].name === name, this.cartShop[i].color === color, this.cartShop[i].material === material) {
            this.cartShop.splice(i, 1);
            break;
        };
    AS_shoppingCart.saveLocalCart();
};

For those who are interested, this is how I store the object instances on the array:

//THE LOGIC FOR THE SHOPPING CART - OOP
var AS_shoppingCart = {};
//cart where the item objects will be stored
AS_shoppingCart.cartShop = [];
//item object and its properties
AS_shoppingCart.Item = function(name, price, quantity, color, material) {
    this.name = name;
    this.price = price;
    this.quantity = quantity;
    this.color = color;
    this.material = material;
};
This is how my HTML looks like. Note, the problem is with these options. In order to delete older cart entries, I have to select the option combination the same as the listed item. Which logically makes sense, but the problem is, I haven't got the slightest clue on how to go around this problem.

                 <div>
                    <h4>Customisation:</h4>
                    <table>
                        <tr>
                          <th>Color</th>
                          <th>Material</th>
                        </tr>
                        <tr>
                          <td>
                            <select id="colors" name="colors">
                               <option data-color="Default">Default</option>
                               <option data-color="Blue">Blue</option>
                               <option data-color="Green">Green</option>
                               <option data-color="Brown">Brown</option>
                             </select>
                           </td>
                           <td>
                             <select id="materials" name="materials">
                                <option data-material="Alloy">Alloy</option>
                                <option data-material="Steel">Steel</option>
                                <option data-material="Carbon Fibre">Carbon Fibre</option>
                                <option data-material="Titanium">Titanium</option>
                              </select>
                            </td>
                         </tr>
                      </table>
                   </div>
                   <div class="button-group">
                       <button class="add-to-cart" data-name="Aluminum road bike " data-price="256">Add to cart</button>
                   </div>

This is the jQuery part where it puts the logic into use. Note; I've cut out the irrelevant parts in the snippet.

$(document).ready(function(){
    /* CART */
        //assigning a click event to DOM object
    $(".add-to-cart").click(function(event){
        //prevents the page from being refreshed
        event.preventDefault();
        //sets the name variable to a clicked data-name
        var name = $(this).attr("data-name");
        //sets the price to the number version of data-price attribute
        var price = Number($(this).attr("data-price"));
        var color = $('#colors option:selected').data('color');
        var material = $('#materials option:selected').data('material');
      
    $(".add-to-cart").attr({
        "data-color" : color,
        "data-material" : material
    });
        AS_shoppingCart.addItem(name, price, 1, color, material);
        displayCart();
    });
    
    $("#show-cart").on("click",".delete-item", function(event){
        var name = $(this).attr("data-name");
        console.log(name);
        AS_shoppingCart.removeItemAll(name);
        displayCart();
    });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

So my question is, how do I go about ensuring that I don't actually have to set my product item options to the older items in the cart in order to delete them.

Thank you.

EDIT: showing my addItem function:

//adds items to the cart
AS_shoppingCart.addItem = function(name, price, quantity, color, material){
    /*checks to see if the item with the identical name exists in the cart
    if so, it will only increment the quantity of the said item (no redundancies)*/
    for(let item of this.cartShop) {
        if(item.name === name && item.color === color && item.material === material) {
            item.quantity += quantity;
            this.saveLocalCart();
            return;
        };
    };
   var item = new this.Item(name, price, quantity, color, material);
    this.cartShop.push(item);
    this.saveLocalCart();
};


Solution

  • It happens because you use break after finding first item in cart. Remove it to keep on iterating through items after finding first of it.

    UPDATE 2

    Also splice will provide change of items count so you better to reverse loop and delete items from last to first or simply use filter like this:

      //now items store shopcart with all items except those you want to remove
      //so you can store it back to this.cartShop or pass to another method to save new version of shopcart which is more acceptable way
    
      let items = this.cartShop.filter(function(item) => {
        return (item.name !== name && 
               item.color !== color && 
               item.material !== material)
      }
    

    So your final code can be like this:

    AS_shoppingCart.removeItemAll = function(name, color, material){
    
          this.cartShop = this.cartShop.filter(function(item){ return !(item.name === name && item.color === color && item.material === material) });
    
          AS_shoppingCart.saveLocalCart();
    };