-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckout.js
More file actions
76 lines (51 loc) · 2.07 KB
/
checkout.js
File metadata and controls
76 lines (51 loc) · 2.07 KB
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
document.addEventListener("DOMContentLoaded", function () {
const checkoutList = document.getElementById("checkout-list");
const checkoutTotal = document.getElementById("checkout-total");
const checkoutForm = document.getElementById("checkout-form");
const errorMsg = document.getElementById("error-msg");
const savedCart = localStorage.getItem("cart");
if (!savedCart) {
checkoutList.innerHTML = "<li>Your cart is empty</li>";
return;
}
const cart = JSON.parse(savedCart);
let totalPrice = 0;
cart.forEach(function(item) {
const li = document.createElement("li");
const itemTotal = item.price * item.quantity;
li.textContent = `${item.name} × ${item.quantity} — ₹${itemTotal}`;
checkoutList.appendChild(li);
totalPrice += itemTotal;
});
checkoutTotal.textContent = totalPrice;
checkoutForm.addEventListener("submit", function (e) {
e.preventDefault();
errorMsg.textContent = "";
const name = document.getElementById("name").value.trim();
const address = document.getElementById("address").value.trim();
const phone = document.getElementById("phone").value.trim();
if (name.length < 3) {
errorMsg.textContent = "Name must be at least 3 characters";
return;
}
if (address.length < 5) {
errorMsg.textContent = "Please enter a valid address";
return;
}
if (!/^\d{10}$/.test(phone)) {
errorMsg.textContent = "Phone number must be 10 digits";
return;
}
const orderDetails = {
customer: { name, address, phone },
cart,
total: totalPrice
};
// Save order for confirmation page
localStorage.setItem("lastOrder", JSON.stringify(orderDetails));
// Clear cart
localStorage.removeItem("cart");
// Redirect to confirmation page
window.location.href = "order-success.html";
});
});