How to have alerts show within a switch [duplicate] - javascript

This question already has answers here:
Javascript number comparison fails
(2 answers)
Closed 4 years ago.
I have made a little test program to show the user what bonus they get from having a certain value. The case statements should function as an OR gate. But the problem shows up when the alert should show up on screen but does not.
I have changing a few values, but that did not work. Also new to using JavaScript so I do not know what I can do as of right now.
var strength = prompt("What is the value of strength?");
switch (strength) {
case 10 :
case 11 :
alert("+0");
break;
case 12 :
case 13 :
alert("+1");
break;
case 14 :
case 15 :
alert("+2");
break;
case 16 :
case 17 :
alert("+3");
break;
case 18 :
case 19 :
alert("+4");
break;
case 20 :
case 21 :
alert("+5");
break;
default : ("Please enter a value between 10 and 20");
}
When the user enters the value of strength the bonus of that value should be showing up.
Example: strength = 12 alert("+1")
The alert does not show up though

Prompt returns a string and you are looking for numbers.
var a = 10
switch (a) {
case 10:
console.log("a - yes");
break;
default:
console.log("a - no");
}
var b = "10"
switch (b) {
case 10:
console.log("b - yes");
break;
default:
console.log("b - no");
}
So either you change your switch to be strings, or you change your prompt to be a number. Many ways to do it.
var strength = Number(prompt("What is the value of strength?"));
var strength = parseInt(prompt("What is the value of strength?"));
var strength = +prompt("What is the value of strength?");

Just convert strength to an integer:
var strength = parseInt(prompt("What is the value of strength?"));
switch (strength) {
case 10 :
case 11 :
alert("+0");
break;
case 12 :
case 13 :
alert("+1");
break;
case 14 :
case 15 :
alert("+2");
break;
case 16 :
case 17 :
alert("+3");
break;
case 18 :
case 19 :
alert("+4");
break;
case 20 :
case 21 :
alert("+5");
break;
default : ("Please enter a value between 10 and 20");
}

You are trying to compare a string strength to an int value e.g:10 and this is because prompt is reading as string.
quote from w3schools:
(Returns) a String. If the user clicks "OK", the input value is returned. If the user clicks "cancel", null is returned. If the user clicks OK without entering any text, an empty string is returned.
What you can do is to use parseInt() function to convert the input to an int like so:
var strength = parseInt(prompt("your message: "));
Here's a short modified version:
var strength = parseInt(prompt("What is the value of strength?"));
switch (strength) {
case 11:
console.log("11");
break;
case 12:
case 13:
console.log("+1");
break;
case 14:
case 15:
console.log("+2");
break;
default : ("Please enter a value between 10 and 20");
}

Related

the difference between switch that tests a variable and a switch that tests a statement [duplicate]

This question already has answers here:
Switch case with conditions
(8 answers)
Closed 2 years ago.
var age = 16;
switch (true) {
case age < 16:
console.log("is a boy, he only drinks juice");
break;
case age >= 16 && age <= 20:
console.log("he can drink beer now ");
break;
default:
console.log("This is not working");
}
var age = 13;
switch (age) {
case age < 16:
console.log("is a boy, he only drinks juice");
break;
case age >= 16 && age <= 20:
console.log("he can drink beer now ");
break;
default:
console.log("This is not working");
}
why the second switch is not working ? and the first one works and how is it possible to make the second switch work ?
switch-case compares equality between the value resulted in the expression and the values defined as cases.
In your first statement the expression is true which is the value you want to compare, so the cases should be case true and case false.
In your code to wrote 'age>=16' etc... These are actually values of true or false, therefore the value in the switch can be compared to the cases.
In your second statement, you try to compare age which is an integer, with cases that are booleans, therefore, no case will be hit.
In your case, switch-case statement isn't suitable to your propose (you can use if-else)

How to correctly write a condition in switch? [duplicate]

This question already has answers here:
javascript switch(true)
(5 answers)
Closed 5 years ago.
Good afternoon!
Why does the first option work - switch (true), and the second option does not work - switch (a)?
First:
var a= prompt('Enter value', '');
switch(true)
{
case a>10:
alert('a>10');
break;
case a<10:
alert('a<10');
break;
default:
alert('a===10');
Second:
var a= prompt('Enter value', '');
switch(a)
{
case a>10:
alert('a>10');
break;
case a<10:
alert('a<10');
break;
default:
alert('a===10');
Why does the first option work - switch (true), and the second option
does not work - switch (a)?
As per documentation
The switch statement evaluates an expression, matching the
expression's value to a case clause, and executes statements
associated with that case.
So, in your first option true will match to either a < 10 or a > 10, however in second option, a being a string may not match to either of them.
Edit: I just realize OP ask for the difference instead of why it won't work, sorry for misunderstanding the question
It should work nicely
var a = prompt('Enter value', '');
switch (true) {
case (a > 10):
alert("a > 10");
break;
case (a < 10):
alert("a < 10");
break;
default:
alert('a == 10');
}
It's because a > 10 is true, like the switch(true), while switch(a) was passed a, which is not true. Of course, you should cast a. a = +a or use parseInt() or parseFloat().
Here's what you probably meant to do:
var a = prompt('Enter value');
if(+a > 10){
alert('a > 10');
}
else if(a !== '' && +a < 10){
alert('a < 10');
}
else if(+a === 10){
alert('a === 10');
}
else{
alert('Really, you should avoid using prompt and alert!');
}
// notice this is less code than that pointless switch
You need to convert the user input from a string to an integer, like so
a = parseInt(a)

How to use switch to compare values between values

I'm learning JavaScript with a very basic and simple Level Upper system by a button using a XP Table to set var named Level a value and print it.
How can I use the switch statement to compare numbers between 10 and 20 as example, and return a var named Level the value of 2(Lv. 2)?
I've tried using "case 10...20" (3 dots as in another languages) but it didn't work!
I tried to use if statement, but it doesn't work properly. :/
var Exp = 1;
var Level = 1;
function MaisExp()
{
Exp++;
document.getElementById("console").innerHTML = "+1 XP! | "+" Total: "+Exp+" xp points";
VerLevel();
}
function VerLevel()
{
switch(Exp)
{
case 0...10: ***< --- dots didn't work.***
{
Level=1;
}
case 20:
{
Level=2;
}
case 40:
{
Level=1;
}
case 80:
{
Level=1;
}
}
document.getElementById("tela").innerHTML = Level;
}
You can use if statements like this:
if(Exp >= 0 && Exp <= 10)
{
}
else if(Exp <= 20)
{
}
else if(Exp <= 30) etc...
The case statement doesn't work with multiple validations, it can only handle one per case. However, you can list multiple cases, for example:
switch(age){
case 0:// If age is 0, it would enter here, since there is no "break;" it goes down to 1
case 1:// Same as above
case 2:// Same as above
case 3:// Since this one has a break, this code is executed and then the switch terminates
console.log('This toy is not right for this person');
break;
default:// This special case fires if age doesn't match any of the other cases, or none of the other cases broke the flow
console.log('This toy is good for this person');
}
So, in your code, it should be something like:
switch(Exp)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
Level=1;
break;
case 20:
Level=2;
break;
case 40:
Level=1;
break;
case 80:
Level=1;
break;
}
But, since you want all to be level 1, but 20, you could also use the default case, like this:
switch(Exp)
{
case 20:
Level=2;
break;
default:
Level=1;
}
While you have already a default value of 1, you could take it in the function and check onle the condition for level = 2.
function VerLevel() {
Level = 1;
if (Exp === 20) {
Level = 2;
}
document.getElementById("tela").innerHTML = Level;
}
I suggest to change the style of variable and function to start with lower case letters, because functions with upper case letters denotes instanciable/constructor functions, which can be uses with new operator.

(JavaScript) Using a switch statement with an input box

New to JavaScript so please forgive me if this has an obvious answer. I'm trying to get a switch statement to output a specific phrase depending on the value of an input box, however it will only output the default option. What have I done wrong? Thanks.
<input id="inputIQ" type="number"/>
<button onclick="inputIQFunction()">Submit</button>
<script>
function inputIQFunction()
{
var userinput = document.getElementById("inputIQ").value;
switch (userinput) {
case userinput <= 10:
alert("Less than 10");
break;
case userinput > 10:
alert("Greater than 10");
break;
default:
alert("Please input value");
break;
}
}
</script>
Basically, switch doesn't support conditional expressions. It just jumps to the value according to the cases.
If you put true in the switch (true) part, it'll jump to the case whose have true value.
Try like this
switch (true) {
case userinput <= 10:
alert("Less than 10");
break;
case userinput > 10:
alert("Greater than 10");
break;
default:
alert("Please input value");
break;
}
You cannot use logical conditions in your switch statement. It actually compares your userinput to a result of condition (true \ false), which never occurs.
Use conditions instead:
function inputIQFunction() {
function getIQFunctionOutput(inputValue) {
var parsedInput = parseInt(inputValue);
if (Number.isNaN(parsedInput))
return "Please, enter a correct value";
return parsedInput <= 10
? "Less or equal than 10"
: "Greater than 10";
}
var userinput = document.getElementById("inputIQ").value;
var output = getIQFunctionOutput(userinput);
alert(output);
}
<input id="inputIQ" type="number" />
<button onclick="inputIQFunction()">Submit</button>
P.S. You can actually use switch with logical statements this way:
switch (true) {
case userinput <= 10:
break;
case userinput > 10:
break;
}
but I would highly recommend not to use this approach because it makes your code harder to read and maintain.
Try like this:
<input id="inputIQ" type="number"/>
<button onclick="inputIQFunction()">Submit</button>
<script>
function inputIQFunction() {
var userinput = document.getElementById("inputIQ").value;
userinput = parseInt(userinput);
switch (true) {
case userinput <= 10:
alert("Less than 10");
break;
case userinput > 10:
alert("Greater than 10");
break;
default:
alert("Please input value");
break;
}
}
</script>
A switch works by testing the value of the expression in switch(expression) against the values of each case until it finds one that matches.
In your code, the userinput in switch(userInput) is a string, but your two case statements both have a value of either true or false. So you want to use switch(true) - that's how you get a switch to work with arbitrary conditions for each case. In context:
switch(true) {
case userinput <= 10:
alert("Less than 10");
break;
case userinput > 10:
alert("Greater than 10");
break;
default:
alert("Please input value");
break;
}
I know this is an old thread but I'm just starting out on JS (one week in) and this is the simplest thing I could create just so the logic is understood.
Switch appears to work only by true/false when using a user input value.
My script looks like:
<script>
document.getElementById("click").onclick = function () {
var day = document.getElementById("day").value;
switch (true) {
case day == 1:
document.write("Monday");
break;
case day == 2:
document.write("Tuesday");
break;
default:
document.write("Please enter valid number")
}
</script>
Like I said I'm only a week into this but I'm making a small portfolio for myself with these little things that courses may not teach, I'm open to any one wishing to offer me help learning also, hope it helps with understanding the logic.
You are not fulfilling the requirements of 'switch & case'
userinput <= 10:
It means 'true'
because '<=' is a comparison operator. It compares 'userinput' and ’10'(given value) and give you an answer in boolean(i.e. true or false).
But, here in switch case you need an integer value.
Another
You have entered this
'switch (userinput)' here 'switch' considering 'userinput' a string that should be integer,
You can fix it with this.
switch (eval(userinput))

Compare strings without being case-sensitive

I have problem with a variable I made (it's a string) in JavaScript. It will be prompt from the user and then with the switch I will check if it is true or not. Then when I input it upper case it will say it is identified as a another var.
Here is my code:
var grade = prompt("Please enter your class") ;
switch ( grade ){
case "firstclass" :
alert("It's 500 $")
break;
case "economic" :
alert("It's 250 $")
break;
default:
alert("Sorry we dont have it right now");
}
Just lower case it initially.
var grade = prompt("Please enter your class").toLowerCase() ;
as #nicael stated just lowercase what they input. However, if you need to preserve the way it was input and only compare using the lowercase equivalent, use this:
var grade = prompt("Please enter your class") ;
switch ( grade.toLowerCase() ){
case "firstclass" :
alert("It's $500");
break;
case "economic" :
alert("It's $250");
break;
default :
alert("Sorry we don't have it right now");
}
You could set the entire string to lower case by using the String prototype method toLowerCase() and compare the two that way.
To keep the input the same, mutate the string during your switch statement:
switch( grade.toLowerCase() ) {
// your logic here
}
You should always compare uppercase string with uppercase values in case sensitive languages.
Or lower with lower.
var grade = prompt("Please enter your class") ;
switch (grade.toUpperCase())
{
case "FIRSTCLASS" :
alert("It's 500 $")
break;
case "ECONOMIC" :
alert("It's 250 $")
break ;
default :
alert("Sorry we dont have it right now");
}

Categories