Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Javascript HTML
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 6:28am
Comments
deepak.m.shrma at 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 at 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 | :laugh:
  Permalink  
Comments
Corrigan_sam at 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 at 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 at 16-Nov-12 11:49am
   
Haha yea, Its good to have people like you on these websites, Thanks again :)
deepak.m.shrma at 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
0 OriginalGriff 7,215
1 DamithSL 5,114
2 Maciej Los 4,866
3 Sergey Alexandrovich Kryukov 4,747
4 Kornfeld Eliyahu Peter 4,514


Advertise | Privacy | Mobile
Web01 | 2.8.141223.1 | Last Updated 16 Nov 2012
Copyright © CodeProject, 1999-2014
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