Why this switch not working?

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

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.

1 Like

Ok how do i convert it to a number?

Thank you very much it worked!

This works too, thank you.

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;