<!
DOCTYPE html>
<html>
<head>
<title>Switch Statement Example</title>
<style>
#colorBox {
width: 200px;
height: 100px;
border: 1px solid black;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>Choose a Color</h1>
<select id="colorSelect" onchange="changeColor()">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
<option value="default">Default</option>
</select>
<div id="colorBox"></div>
<script>
function changeColor() {
const selectedColor = document.getElementById("colorSelect").value;
const colorBox = document.getElementById("colorBox");
switch (selectedColor) {
case "red":
colorBox.style.backgroundColor = "red";
break;
case "blue":
colorBox.style.backgroundColor = "blue";
break;
case "green":
colorBox.style.backgroundColor = "green";
break;
case "yellow":
colorBox.style.backgroundColor = "yellow";
break;
default:
colorBox.style.backgroundColor = "lightgray"; // Default color
break;
}
}
// Initialize with the default color on page load
changeColor();
</script>
</body>
</html>
let selectedFruit = "Apple"; // This could come from user input, a
database, etc.
let message;
switch (selectedFruit) {
case "Banana":
message = "Bananas are a great source of potassium!";
break; // Exits the switch statement
case "Apple":
message = "An apple a day keeps the doctor away!";
break;
case "Orange":
message = "Oranges are packed with Vitamin C.";
break;
default: // Executed if no other case matches
message = "I'm not familiar with that fruit.";
}
console.log(message); // Output: An apple a day keeps the doctor away!
<!DOCTYPE html>
<html>
<head>
<title>Fruit Selector</title>
</head>
<body>
<h1>Choose Your Favorite Fruit</h1>
<input type="text" id="fruitInput" placeholder="Enter a fruit">
<button onclick="getFruitInfo()">Get Info</button>
<p id="fruitOutput"></p>
<script>
function getFruitInfo() {
let fruit =
document.getElementById("fruitInput").value.toLowerCase(); // Get input
and convert to lowercase
let message;
switch (fruit) {
case "apple":
message = "Apples are crisp and delicious!";
break;
case "banana":
message = "Bananas are a great source of potassium.";
break;
case "orange":
message = "Oranges are packed with Vitamin C.";
break;
case "grape":
message = "Grapes are small and juicy.";
break;
default:
message = "I don't have information about that fruit.";
}
document.getElementById("fruitOutput").innerHTML = message;
}
</script>
</body>
</html>