Multiple ChoicesThe switch statement is basically used to execute different sets of statements depending on a choice. For example, an income tax policy may state: charge 10% for those earning less than $10,000 per annum; 20% for those earning less than $20,000 but more than $10,000 per annum; 30% for all others. Below we will take this situation and present a solution.
<html> <head> <title>Multiple Choice Situations</title> </head> <body> Enter your income in the input box below: <form> <input type="text" size="25" name="income"> <input type="button" value="Calculate" onClick="calculateTax(income.value)"> </form> </body> </html>
Some ExplanationYou may not be familiar with a few things used above:
- We have used parseInt to convert a string into integer. Internally, these two things are represented quite differently. When you write your income as “10000”, its different from 10000. The former is a strings while the later is a number. To convert a string into number we can use parseInt(theString). We had to do this conversion because we can’t compare a string with numbers.
- We don’t need to enclose a statement after an if construct, if that is the single statement to be executed when the if condition is true.
- The button in the form that calls the function calculateTax passes income.value to the function. This is done because income is a textbox while the function works on a string. Doing parseInt on a textbox doesn’t make sense.