-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample9.html
More file actions
81 lines (71 loc) · 2.49 KB
/
Example9.html
File metadata and controls
81 lines (71 loc) · 2.49 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
77
78
79
80
81
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example 9</title>
</head>
<body>
<h3>Example 9</h3>
<label for="additem">Enter Item Name</label>
<input type="text" id="itemname"><br>
<label for="addquantity">Enter Quantity</label>
<input type="text" id="itemqty"><br>
<label for="addprice">Enter Price/KG</label>
<input type="text" id="itemprice"><br>
<button onclick="addItem()">Add Item</button><br>
<p>Total Cost :</p><br>
<p id="totalCost">$0.00</p>
<script>
class Basket {
constructor() {
this.items = [];
}
addItem(product, qty, price)
{
this.items.push({ product, qty, price });
}
calculateSum()
{
let totalCost = 0;
for (let item of this.items) {
totalCost += item.price * item.qty;
}
return totalCost;
}
}
let basket = new Basket();
function addItem()
{
const itemInput = document.getElementById("itemname");
const itemQty = document.getElementById("itemqty");
const itemPrice = document.getElementById("itemprice");
const itemName = itemInput.value.trim();
const itemQuantity = parseFloat(itemQty.value.trim());
const itemPriceValue = parseFloat(itemPrice.value.trim());
if (itemName === "")
{
alert("Please enter an item name.");
}
else if (isNaN(itemQuantity) || itemQuantity <= 0)
{
alert("Please enter a valid quantity.");
}
else if (isNaN(itemPriceValue) || itemPriceValue <= 0)
{
alert("Please enter a valid price.");
}
else
{
basket.addItem(itemName, itemQuantity, itemPriceValue);
const total = basket.calculateSum();
document.getElementById("totalCost").innerHTML = "$" + total.toFixed(2);
// Clear input fields
itemInput.value = "";
itemQty.value = "";
itemPrice.value = "";
}
}
</script>
</body>
</html>