Reputation: 697
I'm trying to use input type="number" and swich together. When I write the number 2 (or some other) in the input field and press button go I hope to get the output "something 2" but I get "undefined".
see my code for html:
<body>
<form>
<input type="number" id="entr">
<input type="button" onclick="func()" value="go">
</form>
<p5 id="demo"></p5>
and for js:
function func() {
var x;
var a = document.getElementById("entr").value;
switch (a) {
case 0:
x = "something 0";
break;
case 1:
x = "something 1";
break;
case 2:
x = "something 2";
break;
case 3:
x = "something 3";
break;
}
document.getElementById("demo").innerHTML = x;
}
When I use default in the switch it execute that code block but never one of the oder code. thanks for answer
Upvotes: 0
Views: 765
Reputation: 5056
While your input type is "number", the Javascript still treats it as a string by default. (Note that you're free to type arbitrary text into your input field.) You have two options: you can switch on the string value...
switch (a) {
case "0":
x = "something 0";
break;
case "1":
x = "something 1";
break;
case "2":
x = "something 2";
break;
case "3":
x = "something 3";
break;
}
That works, but it would be better to parse the input string as a number...
var a = parseInt(document.getElementById("entr").value);
The unary + operator could work as well, but is less robust than the parseInt
function...
var a = +document.getElementById("entr").value;
Upvotes: 2
Reputation: 24229
change
var a = document.getElementById("entr").value;
to
var a = parseInt(document.getElementById("entr").value, 10);
Upvotes: 1