switch case

Tests a condition against any number of case conditions.

 

Break must be used to terminate the switch, or the next statement will be executed.

 

A default case is utilised for when no condition is met.

 

This example asks the user to enter a value in a dialogue box and then checks it against the values in the switch case code block:

<html>
	<head>
		<title>JavaScript</title>
	</head>
	<body>
	<script type="text/javascript">
			var value = prompt("Please enter a value between 1 and 5: ", "Please enter your number here.");

			switch (value) {
				case '1':document.write("You entered 1");
				break;

				case '2':document.write("You entered 2");
				break;

				case '3':document.write("You entered 3");
				break;

				case '4':document.write("You entered 4");
				break;

				case '5':document.write("You entered 5");
				break;

				default: document.write("Unknown value!");
			}
			</script>
	</body>
</html>

Save & refresh browser:

You entered 5

Leave a Reply