1

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>
2
  • 1
    What have I done wrong? - you tell me. In what way is the code not working as intended? Commented Nov 1, 2016 at 3:11
  • just use an if/else chain it's more suited for this situation, you don't have to use a switch case for everything. Commented Nov 1, 2016 at 6:40

6 Answers 6

3

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

"You have make it int before putting into the condition." - the unary plus doesn't convert to "int", it converts to a number, but in any case the <= and > operators will do this automatically (as long as one of their operands is a number).
Thanks for the info @nnnnnn
1

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.

4 Comments

Your code doesn't include the OP's default option for when the value is not <=10 or > 10.
@nnnnnn I have excluded this since value property of input type='number' always returns number, even if empty. So, there is no way for this default case to fire.
The .value will be a string even when a number is entered. If empty it returns an empty string. Also, in Chrome, for example, you can paste a non-number and then the .value seems to return as an empty string.
@nnnnnn Ok, you are right. I have updated my answer.
1

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>

Comments

0

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;
}

Comments

0

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.

3 Comments

This answer has shortcomings: 1: It is not an answer to OPs question. If you are not answering the question then post a comment. 2: You do not understand the operation of the switch statement: switch is very simple, you provide a value to be checked, and the switch function matches that value against each of the given cases. If no cases match, then the default is chosen. You could have used switch( day ) then used case 1, case 2: ... etc. which would have been better code.
As mentioned on the post, I was in my starting week of JS and that is a method I found worked for what I was trying to achieve in understanding how its possible to print a string associated to a case, I'd already attempted switch (day) as you mentioned and the output was not printing the string of day associated to the case so yes it would have been better code however it was not working for me in that time and therefore I created a work around which means the OP could see another possible example of how to achieve the desired outcome, I appreciate your comment though.
Sure, I understand. Sorry if I sounded critical, I was just trying to give you more info on posting on SO and a bit more about switch(). Keep contributing to SO and learning js!
0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.