Search code examples
javascriptjqueryshopping-cartstatic-site

Duplicate items appearing in shopping cart


I'm trying to basically build a shopping cart on a static site. Items are displayed on a table. I built this shopping cart from scratch, no external jQuery shopping cart libraries used.

There's one feature I can't seem to get to work: When a user adds an item that already exists in the shopping cart, it should only increase the quantity instead of adding the item to the table.

Here's a JSFiddle link with everything I've implemented so far and a working demo, but you can also see the code below.

Here's the JS that adds the item:

$( "#addBtn" ).click(function() {
  var item = $("#orderMenu option:selected").text();
  var qty = $("#orderQty option:selected").text();

  var newRowContent = "<tr><td>" + qty + "</td><td>" + item + "</td>";

  $("#cart-info tbody").append(newRowContent);
});

Here's the simplified HTML, for the sake of simplicity:

<table class="table" id="cart-info">
    <thead>
        <tr>
            <th>#</th>
            <th>Item</th>
        </tr>
    </thead>
    <tbody>

    </tbody>
</table>

<select id="orderMenu">
    <option>Foo</option>
    <option>Bar</option>
</select>

<select id="orderQty">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

<button id="addBtn">ADD TO CART</button>

Here's the pseudocode I'd like to convert to jQuery but have no idea how.

(Apologies for the weird pseudocode/jQuery hybrid, I'm still learning jQuery)

for each <td> in #cart-info {
    if (<td>.html() == item) {
        qtyCell = the previous <td>
        oldQty = Number(qtyCell.text())
        newQty = oldQty + qty
        qtyCell.html(newQty)
        exit for loop
    }
}

The website itself is written purely in HTML/CSS/JS, so it is a completely static site.

Thank you very much in advance!


Solution

  • Check this fiddle
    new fiddle Use the value of each option to determine if it has already been added to the table:

    $( "#addBtn" ).click(function() {
      var item = $("#orderMenu option:selected").text();
      var item_val = $("#orderMenu").val();
      var qty = $("#orderQty option:selected").text();
    
      var newRowContent = "<tr><td class='qty'>" + qty + "</td><td data-val='"+item_val+"'>" + item + "</td>";
      if ($("#cart-info tbody [data-val='"+item_val+"']").length < 1)
          $("#cart-info tbody").append(newRowContent);
        else {
            var new_qty = parseInt($("#cart-info tbody [data-val='"+item_val+"']").prev('.qty').text())+parseInt(qty);
            $("#cart-info tbody [data-val='"+item_val+"']").prev('.qty').text(new_qty);
        }
    });
    

    EDIT:

    fixed fiddle url

    EDIT 2

    new fiddle updating quantities