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?


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


function myFunction() {
  var x = document.getElementById("day").value;
  var text;
  switch(x) {
    case 0:
      text = "Today is Monday";
    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:

   text = 'No match';

or similar.

1 Like

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.

1 Like

Ok how do i convert it to a number?

Look at Number or parseInt functions on MDN.

1 Like

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


this transform a string to a number;

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