Why this switch not working?

Why this switch not working?
0.0 0

#1

Im trying to make a function when user types i.e. 0 to display “Today is Monday”. But i dont know why when i type down 0 or 1 it gives me “Undefined”. What am i doing wrong?

HTML:

<html>
<body>
 <input type="text" id="day" value="day"><br><br>
  <button type="submit" onclick="myFunction()">Click</button>
  <p id="demo"></p>
</body>
</html>

JavaScript:

function myFunction() {
  
  var x = document.getElementById("day").value;
  var text;
  
  switch(x) {
    case 0:
      text = "Today is Monday";
      break;
    case 1:
      text = "Today is Thuesday";
   }
  document.getElementById("demo").innerHTML = text;
  
}

#2

I think it is because x (the value from the input) is a string and you are checking for numbers.+
I would make these changes:
instead of case 0: case '0', etc.
And add a default case, for example:

default:
   text = 'No match';

or similar.


#3

As @zdflower points out, document.getElementById(“day”).value is a string and not a number. Convert it into a number before assigning it to the x variable.


#4

Ok how do i convert it to a number?


#5

Look at Number or parseInt functions on MDN.


#6

Thank you very much it worked!


#7

This works too, thank you.


#8

I think is better the solution of zdflower where you use ‘0’ and ‘1’ and not the number, and for the rest use a default; but if you want to convert to a number, you can use parseInt(). In this example, you can use

switch(parseInt(x)) 
code
}

this transform a string to a number;


#9

Out of curiosity, why do you think it is better to use strings instead of numbers for the cases?