3 Use JavaScript for doing client – side validation of the pages implemented in experiment
1 and experiment 2.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Shopping Cart</title>
<style>
/* Basic CSS with Flexbox for layout */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
align-items: center;
header {
background-color: #333;
color: #fff;
padding: 10px;
width: 100%;
text-align: center;
.container {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
padding: 20px;
max-width: 800px;
.product {
border: 1px solid #ddd;
padding: 10px;
margin: 10px;
text-align: center;
.cart {
border: 1px solid #333;
padding: 10px;
width: 300px;
</style>
</head>
<body>
<header>
<h1>Simple Shopping Cart</h1>
</header>
<div class="container">
<!-- Product Catalog -->
<div class="product">
<h2>Product 1</h2>
<p>Price: $10</p>
<input type="number" id="quantity1" placeholder="Quantity" min="1">
<button onclick="addToCart('Product 1', 10)">Add to Cart</button>
</div>
<div class="product">
<h2>Product 2</h2>
<p>Price: $15</p>
<input type="number" id="quantity2" placeholder="Quantity" min="1">
<button onclick="addToCart('Product 2', 15)">Add to Cart</button>
</div>
<!-- Shopping Cart -->
<div class="cart">
<h2>Shopping Cart</h2>
<ul id="cart-items"></ul>
<p>Total: $<span id="cart-total">0</span></p>
</div>
</div>
<script>
// JavaScript for handling the shopping cart
let cartItems = [];
let cartTotal = 0;
function addToCart(productName, price) {
const quantityField = document.getElementById(`quantity${productName.charAt(8)}`);
const quantity = parseInt(quantityField.value);
// Validate quantity
if (isNaN(quantity) || quantity < 1) {
alert("Please enter a valid quantity (1 or more).");
return;
// Add to cart
cartItems.push({ productName, price, quantity });
cartTotal += price * quantity;
// Update the cart display
updateCartDisplay();
function updateCartDisplay() {
const cartItemsElement = document.getElementById('cart-items');
const cartTotalElement = document.getElementById('cart-total');
// Clear existing cart display
cartItemsElement.innerHTML = '';
// Populate cart display with current items
cartItems.forEach(item => {
const listItem = document.createElement('li');
listItem.textContent = `${item.productName} (Quantity: ${item.quantity}): $${item.price *
item.quantity}`;
cartItemsElement.appendChild(listItem);
});
// Update total price
cartTotalElement.textContent = cartTotal;
</script>
</body>
</html>
Output: