The field to be tested is specified in the switch statement itself and all of the code for the switch is contained within a block.
Each individual value you want to test for is specified as a label after the keyword 'case' and that is then followed by the statements for the path that is to be followed when that value is in the field. All of the following statements are then run until a break statement is reached at which point the processing jumps to the next statement after the end of the block. A default label at the end of the block provides a catchall for when the field contains any value other than those specifically mentioned in a case.
Note that if no break is specified then the code will fall through and continue running all of the following statements. This can lead to errors where the code falls though by accident and it is therefore considered poor coding practice to allow the code to fall through. At the very least you should comment where the fallthrough is deliberate so that it does not get misidentified as the possible cause of an error.
Note that to test this example try adding a ? followed by a colour to the end of the address of the page - example11.html?red
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example 11</title>
</head>
<body>
<div id="ex"></div>
<script type="text/javascript" src="example11.js"></script>
</body>
</html>
JavaScript
var colour, code;
colour = window.location.search.substring(1);
switch (colour) {
case 'red':
code = '#ff0000';
break;
case 'green':
code = '#00ff00';
break;
case 'blue':
code = '#0000ff';
break;
default:
code = 'unknown';
}
document.getElementById('ex').innerHTML = code;