The switch Construction in Action : Switch « Language Basics « JavaScript DHTML

The switch Construction in Action

JavaScript Bible, Fourth Edition
by Danny Goodman 

John Wiley & Sons CopyRight 2001

<TITLE>Switch Statement and Labeled Break</TITLE>
<SCRIPT LANGUAGE="JavaScript1.2">
// build two product arrays, simulating two database tables
function product(name, price) { = name
    this.price = price
var ICs = new Array()
ICs[0] = new product("Septium 900MHz","$149")
ICs[1] = new product("Septium Pro 1.0GHz","$249")
ICs[2] = new product("Octium BFD 750MHz","$329")
var snacks = new Array
snacks[0] = new product("Rays Potato Chips","$1.79")
snacks[1] = new product("Cheezey-ettes","$1.59")
snacks[2] = new product("Tortilla Flats","$2.29")
// lookup in the 'table' associated with the product
function getPrice(selector) {
    var chipName = selector.options[selector.selectedIndex].text
    var outField = document.forms[0].cost
        switch(selector.options[selector.selectedIndex].value) {
            case "ICs":
                for (var i = 0; i < ICs.length; i++) {
                    if (ICs[i].name == chipName) {
                        outField.value = ICs[i].price
                        break master
            case "snacks":
                for (var i = 0; i < snacks.length; i++) {
                    if (snacks[i].name == chipName) {
                        outField.value = snacks[i].price
                        break master
                outField.value = "Not Found"
<B>Branching with the switch Statement</B>
Select a chip for lookup in the chip price tables:<P>
Chip:<SELECT NAME="chips" onChange="getPrice(this)">
    <OPTION VALUE="ICs">Septium 900MHz
    <OPTION VALUE="ICs">Septium Pro 1.0GHz
    <OPTION VALUE="ICs">Octium BFD 750MHz
    <OPTION VALUE="snacks">Rays Potato Chips
    <OPTION VALUE="snacks">Cheezey-ettes
    <OPTION VALUE="snacks">Tortilla Flats
    <OPTION>Poker Chipset
Price:<INPUT TYPE="text" NAME="cost" SIZE=10>


Related examples in the same category

1.Switch statement
2.The switch Statement
3.Another switch Statement
4.Use switch with true false value
5.Switch with string value
6.Switch based on integer value