Click here to Skip to main content
12,954,672 members (72,595 online)
Rate this:
 
Please Sign up or sign in to 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:

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 16-Nov-12 5:28am
Comments
deepak.m.shrma 18-Nov-12 22:26pm
   
LOL.. :-D jst a silly mistake. every beginner face in starting :-)
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Change it into this:
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.
  Permalink  
Comments
Corrigan_sam 16-Nov-12 11:40am
   
Thanks man, Simple mistake i guess! Ahh well we've all got to start somewhere!
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

It's pretty easy to fix - are you sure you can't see it yourself?

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


We've all done it! :laugh:
  Permalink  
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)

    Print Answers RSS
Top Experts
Last 24hrsThis month
OriginalGriff 6,539
CHill60 3,490
Maciej Los 3,153
ppolymorphe 2,030
Jochen Arndt 1,975


Advertise | Privacy | Mobile
Web01 | 2.8.170525.1 | Last Updated 16 Nov 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100