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?
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:
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