1

It gives always answer "Hello City" although i pressed 1 and 2.. what is wrong with the code? what is better to use ? if else statement or switch statement? anyone can help?

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<script type="text/javascript">

function number()
{

var number;
number=document.getElementById('m').value;

switch (number)
{
case 1:
day="Hello World";
break;

case 2:
day="Hello Asia";
break;

default :
day="Hello City";


}
document.write(day);

}


</script>

<input type="number" name="" id="m">
<input type="submit" name="Click" onclick="number()">
</body>
</html>
0

2 Answers 2

4

Cast the value explicitely to a number otherwise it will be a string, the Switch statements in Javascript always use strict type checking (===), thus your example will always return the default value.

var number= +document.getElementById('m').value;
Sign up to request clarification or add additional context in comments.

4 Comments

it worked ...but i did not get this yet. we dont have to tell javascript it is number or string just like we do in php.javascirpt does't get the data type by its own ?
@YousafFarooq All value properties on DOM elements are strings. You will have to explicitly cast the value to another data type if you want to treat it as such.
@YousafFarooq i've edited my answer. there's no type coercion in the switch statements, so you have to match the type as well :)
@YousafFarooq and do you think, that "20" == "XX" should be true? Because both are twenty, one in Arabic, and one in Roman numerals.
0

What about parse to integer.

var number=parseInt(document.getElementById('m').value)

Switch testing strict quality. So there is used triple equals.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.