Pretty straight-forward what I want to do:
- If the input is
0
, it means that they didn't input a number and it should tell you so. - When the input is
7
, it should say that you got it right. - Anything else, it should tell you that you got it wrong.
But it just outputs the "7 is correct" line no matter what the input is, and I can't figure it out what is wrong.
<script type="text/javascript">
function problem2 ()
{
var number = 0;
var text=document.getElementById("output");
number = prompt("Enter a number between 1 and 10 please" , 0);
if (number = 0)
{
text.value = "You didn't enter a number!";
}
if (number = 7)
{
text.value = "7 is correct!";
}
else
{
text.value = "Sorry, ", input, "is not correct!";
}
}
</script>
<input type="button" value="Click here" onclick="problem2()">
<input id="output" type="text">
You are using assignment operators as your conditionals instead of comparison operators:
Alternatively you can use a switch and organize the conditionals a bit easier:
You're assigning with
=
. Use==
or===
.Also, be wary of your brace placement. Javascript likes to automatically add semicolons to the end of lines. Source.
Here is a code with the some fixes and improvements (I commented what I changed):
Aditionally, two more changes can be made:
var
(e.gvar something = "", somethingElse = 99;
)var msg = "default"
and remove theelse
Note: an undocumented change I made was to rename some vars, I encourage everyone to stop using vars like
number, text, string
, if you have this bad habit, you will eventually use illegal var names by mistake.