Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

Javascript if statements not working

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">
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're assigning with =. Use == or ===.

if( 0 == number ){

  text.value = "You didn't enter a number!";
}

Also, be wary of your brace placement. Javascript likes to automatically add semicolons to the end of lines. Source.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...