+ 2

If and else statements is not working properly,as I want.

Plz help me...🙏🙏🙏🙏 Try and fix problem <h1 id="dis"></h1> <input type="number" id="ans" onchange="result()"/> <script type="text/javascript"> var x=Math.floor(Math.random()*100); var y=Math.floor(Math.random()*100); document.getElementById("dis").innerHTML=x+"+"+y; var z=document.getElementById("ans"); var r=eval(x+y); function result(){ if (z=r) { alert("you are correct"); } else { alert("you are wrong"); } } </script>

30th Jul 2017, 4:35 PM
Ankur Dutta Jha
Ankur Dutta Jha - avatar
5 Answers
+ 3
Okay! So. First problem, obviously, was that on your statement '(if z = r )' was incorrect. This is a declaration. If you want to figure if something is equal to something else, use '==' or '===' (I prefer '==='). The next problem is, your statement 'z = document.getElementById("ans"); ' does not return the value of the 'ans' input, but rather just the element itself. To get the value, you'd want to use 'var z = document.getElementById('ans').value;'. However, we will encounter another problem where the variable z will only become this value ONCE (when the page is ran), as all the code is only ran once unless you call it again (like you do when you call 'result()' with 'onchange'). Since the input 'ans' always starts out empty, z will always be empty. So, you'll want to move that code down into your 'result()' function. That way, the variable z will update every time the 'result()' function is called. Finally, we'll encounter one last issue. 'document.getElementById('ans').value' will not return a number, but rather a string that represent a number. So instead of a real 15, you'll get "15". As such, the value of z will never be equal to the value or r. One way to fix this is by evaluating the string we get. In other words: 'z = eval(document.getElementById("ans").value);'. After all this, your code should be working properly.
30th Jul 2017, 5:33 PM
Christian Barraza
Christian Barraza - avatar
29th Nov 2017, 1:25 AM
Ankur Dutta Jha
Ankur Dutta Jha - avatar
+ 2
@slak I had tried this. Then else works(z==r) If work (z=r) But both doesn't work
30th Jul 2017, 4:45 PM
Ankur Dutta Jha
Ankur Dutta Jha - avatar
+ 1
maby change if(z=r) to if(z==r)
30th Jul 2017, 4:43 PM
Slak
Slak - avatar
+ 1
I don't know man 😓 if z == r the output should be "you are correct" and if z != the output should be "you are wrong"
30th Jul 2017, 4:52 PM
Slak
Slak - avatar