-
Notifications
You must be signed in to change notification settings - Fork 0
/
co_cart.js
83 lines (67 loc) · 2.18 KB
/
co_cart.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"use strict";
/*
New Perspectives on HTML5, CSS3, and JavaScript 6th Edition
Tutorial 13
Review Assigment
Shopping Cart Form Script
Author: Hesbon Osoro
Date: 12/10/22
Filename: co_cart.js
Function List
=============
calcCart()
Calculates the cost of the customer order
formatNumber(val, decimals)
Format a numeric value, val, using the local
numeric format to the number of decimal
places specified by decimals
formatUSACurrency(val)
Formats val as U.S.A. currency
*/
/* Event Listeners */
window.addEventListener("load", function () {
calcCart();
var cart = document.forms.cart;
cart.elements.modelQty.onchange = calcCart;
var shippingOptions = document.querySelectorAll('input[name="shipping"]');
for (var i = 0; i <= shippingOptions.length; i++) {
shippingOptions[i].onclick = calcCart;
}
});
function calcCart() {
var cart = document.forms.cart;
var orderCost = cart.elements.modelCost.value * cart.elements.modelQty.value;
cart.elements.orderCost.value = formatUSCurrency(orderCost);
var shipCost =
document.querySelector('input[name="shipping"]:checked').value *
cart.elements.modelQty.value;
cart.elements.shippingCost.value = formatNumber(shipCost, 2);
cart.elements.subTotal.value = formatNumber(orderCost + shipCost, 2);
var salesTax = 0.05 * (orderCost + shipCost);
cart.elements.salesTax.value = formatNumber(salesTax, 2);
cart.elements.cartTotal.value = formatUSCurrency(
/**
* FIXME: Use this on step 5
*/
orderCost + shipCost + salesTax
/**
* FIXME: Use this on step 5
*/
// roundToTwo(orderCost) + roundToTwo(shipCost) + roundToTwo(salesTax)
);
cart.elements.shippingType.value = document.querySelector(
'input[name="shipping"]:checked'
).labels[0].textContent;
}
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
function formatNumber(val, decimals) {
return val.toLocaleString(undefined, {
minimumFractionDigits: decimals,
maximumFractionDigits: decimals,
});
}
function formatUSCurrency(val) {
return val.toLocaleString("en-US", { style: "currency", currency: "USD" });
}