-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshoppingcart.js
60 lines (48 loc) · 1.46 KB
/
shoppingcart.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
$(document).ready(function() { // jQuery wrapper
// Shopping Cart Code
// sets a default price attribute for each item
$('.cart-info').each( function(index) {
var price = $(this).children(".price").html();
price = price.slice(1);
price = parseFloat(price);
$(this).attr("price", price);
});
// clicking on the quantity number inputs change the price attibute for an item and call updateTotal
$('.quantity').each( function(index) {
$(this).click( function() {
var checkout_obj = $(this).parents(".cart-info");
var price = checkout_obj.children(".price").html();
price = price.slice(1);
price = parseFloat(price);
var quantity = $(this).prop("value");
var totalPrice;
if (quantity >= 1) {
totalPrice = price * quantity;
}
checkout_obj.attr("price", totalPrice);
updateTotal();
});
});
$('.remove-item').each( function(index) {
$(this).click( function(event) {
event.preventDefault();
var checkout_obj = $(this).parents(".cart-info");
checkout_obj.attr("price", "0");
var entry = checkout_obj.parents("li");
entry.remove();
updateTotal();
});
});
// updates the total price
function updateTotal() {
var newTotal = 0;
$('.cart-info').each( function(index) {
newTotal += parseFloat($(this).attr("price"));
});
newTotal = newTotal.toFixed(2);
$("#total").html("Item total: $" + newTotal);
}
$('.quantity').keypress(function(e){
if ( e.which == 13 ) e.preventDefault();
});
});