In the previous post, you learned that the conditional statements can change the direction or flow of the program. One type of conditional statement use if-else structure. Another type of conditional statement is called the switch-case statement.
A user input the choice from a given set of options and switch receives the input. The switch matches the input value to a number of cases and when a case matches, it executes the commands in that case.
The switch-case is preferred over if-else whenever you like to give a lot of choices to your users.
Step 1: Open Notepad and create a new file called switch.txt and save it.
var fruits = document.getElementById("myInput").value;
document.write("<h1>" + "This is first choice!" + "</h1>");
document.write("<h1>" + "This is second choice!" + "</h1>");
document.write("<h1>" + "This is third choice!" + "</h1>");
document.write("<h1>" + "Wrong choice! Try again" + "</h1>");
Step 1: Open Notepad document and save it as ex07.txt inside the Exercise-07 folder.
Step 2: Open the notepad and insert the following HTML code.
Your final HTML page should look like following.
Step 5: Save the file- ex07.txt as ex07.html and close it.
Output of the HTML Page
When you open the ex07.html in a browser, you will get an input textbox and a submit button.
Enter 1, 2, or 3 as a choice and the result will be displayed on the screen.