I need help with removing an item from the cart without deleting the entire cart, and also adjusting the price if the customer has a coupon or exceeds a certain quantity. I am working on this using JavaScript before implementing it in Django. Here is the HTML code along with some JavaScript, please let me know if you have any suggestions.
HTML
<div data-name="name" data-price="250" data-id="2">
<img src="x.jpg" alt="" />
<h3>name</h3>
<input type="number" class="count" value="1" />
<button class="tiny">Add to cart</button>
</div>
<script type="text/template" id="cartT">
<% _.each(items, function (item) { %>
<div class="panel">
<h3> <%= item.name %> </h3>
<span class="label">
<%= item.count %> piece
<% if(item.count > 1) {%>
s
<% } %> for <%= item.total %>$</span>
</div>
<% }); %>
</script>
JavaScript
addItem: function (item) {
if (this.containsItem(item.id) === false) {
this.items.push({
id: item.id,
name: item.name,
price: item.price,
count: item.count,
total: item.price * item.count
});
storage.saveCart(this.items);
} else {
this.updateItem(item);
}
this.total += item.price * item.count;
this.count += item.count;
helpers.updateView();
},
containsItem: function (id) {
if (this.items === undefined) {
return false;
}
for (var i = 0; i < this.items.length; i++) {
var _item = this.items[i];
if (id == _item.id) {
return true;
}
}
return false;
},
updateItem: function (object) {
for (var i = 0; i < this.items.length; i++) {
var _item = this.items[i];
if (object.id === _item.id) {
_item.count = parseInt(object.count) + parseInt(_item.count);
_item.total = parseInt(object.total) + parseInt(_item.total);
this.items[i] = _item;
storage.saveCart(this.items);
}
}
}