Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript if statements not working [duplicate]

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">
like image 808
xjsc16x Avatar asked Dec 13 '12 01:12

xjsc16x


People also ask

Can you have 2 IF statements in a function JavaScript?

You can have as many else if statements as necessary. In the case of many else if statements, the switch statement might be preferred for readability. As an example of multiple else if statements, we can create a grading app that will output a letter grade based on a score out of 100.

What is Ifelse in JavaScript?

The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.

Why is my else statement not working Java?

If you are getting an error about the else it is because you've told the interpreter that the ; was the end of your if statement so when it finds the else a few lines later it starts complaining. A few examples of where not to put a semicolon: if (age < 18); if ( 9 > 10 ); if ("Yogi Bear".


1 Answers

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.

like image 196
Josh Avatar answered Nov 09 '22 03:11

Josh