Used switch method to display an alert box to user after entering number. But no output is coming | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Used switch method to display an alert box to user after entering number. But no output is coming

<!DOCTYPE html> <html> <head> <title>hi</title> <script type="text/javascript"> var userInput = prompt("Enter a number":, " "); switch(userInput) { case 1: alert("Number is one"); break; case 2: alert("Number is two"); break; case 3: alert("Number is three"); break; default: alert("Number is not between 1 and 3"); break; } </script> </head> <body> <form id=""> <button onclick="userInput()"></button> </form> </body> </html>

26th Jul 2020, 10:57 AM
Avinash
6 Answers
+ 4
Avinash Make the cases character like '1', '2', '3'. Prompt takes in string by default.
26th Jul 2020, 11:22 AM
Lakshay Mittal
Lakshay Mittal - avatar
+ 3
There are several problems in your code: 1) The onclick attribute executes a *function*. But in your code you declared userInput it as a *input variable* not function or function variable (userInput = prompt(…)) This only takes input from user when you run it and not act as a event handler function. 2) you should insert ':' inside the string and also leave the default text for input empty or "" (prompt ("Enter a number:", "")) This is the corrected code: https://code.sololearn.com/W1XBeSBdb2ci/?ref=app
26th Jul 2020, 11:17 AM
Roopesh
Roopesh - avatar
+ 2
Thanks for the help but your solution is not fully operational. It is taking default case irrespective of input
26th Jul 2020, 11:20 AM
Avinash
+ 2
Avinash surround it with parseInt function (*fix)
26th Jul 2020, 11:22 AM
Roopesh
Roopesh - avatar
+ 2
Yes done. Lots of love
26th Jul 2020, 11:26 AM
Avinash
26th Jul 2020, 11:19 AM
Roopesh
Roopesh - avatar