Easy JavaScript - Switch Statements
EasyProgramming.net Tutorial on Switch Statements
by Nazmus Nasir
HTML
<!-- Easy JavaScript # 21 - switch statements -->
<p>
Welcome to the 21st Easy JavaScript tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. We continue looking at conditional statements called <code>switch</code>.
</p>
<p>
<code>switch</code> statements also allows you to create custom workflows based on input. Unlike the <code>if...else</code> statement, we don't use boolean to check to see if something matches or doesn't. We used <code>switch</code> to get an exact match. For example, picking between a shirt and gloves.
</p>
<p>
Creating conditional statements will allow you to create and manage custom workflows for you and your users. There is always more than one way to use a web application,
</p>
<h2>
Syntax of a switch statement:</h2>
<p>
<code><pre>
switch(item to analyze){
case "condition1":
execute this code;
break;
case "condition2":
execute this code;
break;
case "condition3":
case "condition4":
execute this code;
break;
default:
execute this code if all other cases do not match;
break;
}
</pre>
</code>
</p>
<p>
<h2>
Let's practice:</h2>
Item: <input type="text" id="item" /> <button id="submit">Submit</button><br /><br />
It costs $<span id="price">___</span>
<br /><br />
JavaScript
var button = document.getElementById("submit");
button.onclick = function(){
var item = document.getElementById("item").value;
var price;
switch(item){
case "shirt" :
price = 10;
break;
case "gloves":
price = 5;
break;
case "shoes":
case "socks":
price = 3;
break;
default:
price = "Could not be found";
break;
}
document.getElementById("price").innerText = price;
}