Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi, I have been trying to get a system working where a random number is calculated, then a statement is written to the screen depending on the number that was generated, so in theory it should put a random statement on the screen when the page is refreshed.
However, When i refresh the page it always prints the first statement, and no others, There are no error's so i cannot work out why it is like this. Here is my code:

JavaScript
var fact;
	fact = Math.ceil(Math.random()*4)
	
	if (fact = 1) {
		document.write('Hi');
	}else if(fact = 2){
		document.write('Nope');

So basically there are two more statements after that, But i cant understand why it only writes the first statement, and no others.
Posted
Comments
deepak.m.shrma 18-Nov-12 22:26pm    
LOL.. :-D jst a silly mistake. every beginner face in starting :-)

Change it into this:
JavaScript
var fact;
	fact = Math.ceil(Math.random()*4)
	
	if (fact == 1) {
		document.write('Hi');
	}else if(fact == 2){
		document.write('Nope');


With an == operator, you compare objects and with an = operator, you set the value of an object.
In your code, you didn't compare the two variables, but you did set the fact variable to 1 in your first if statement.
 
Share this answer
 
Comments
Corrigan_sam 16-Nov-12 11:40am    
Thanks man, Simple mistake i guess! Ahh well we've all got to start somewhere!
It's pretty easy to fix - are you sure you can't see it yourself?

Ok:
JavaScript
if (fact = 1) {
Becomes
JavaScript
if (fact == 1) {


We've all done it! :laugh:
 
Share this answer
 
Comments
Corrigan_sam 16-Nov-12 11:39am    
Ahh man thanks a lot, I knew it would be something simple! At least there's websites like this one to help me learn!
OriginalGriff 16-Nov-12 11:45am    
You're welcome! As I said, we've all done it. The other annoying "goodie" is
if (myVariable == 1);
DoThis();

:doh:
Corrigan_sam 16-Nov-12 11:49am    
Haha yea, Its good to have people like you on these websites, Thanks again :)
deepak.m.shrma 18-Nov-12 22:25pm    
Lol... :-P

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900