3 Replies - 835 Views - Last Post: 15 June 2009 - 06:24 AM

#1 DeceitfulPillow   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 35
  • Joined: 22-June 08

Help with Random Number Generators

Posted 14 June 2009 - 11:26 PM

Hey, I'm trying to get this random number gen. to display images upon refresh and I'm having some troubles.
First off, in firefox, it brings up a pop-up and asks to resend the information. Second, only the alternate text shows up and it appears as though the image is a broken link.

Here's the source.


<td colspan="2" rowspan="7">
			<script language="Javascript">
<!--
image = new Array
image[1]="<img src='/images/image1.gif' width='139' height='162' alt='image1' />"
image[2]="<img src='/images/image2.gif' width='139' height='162' alt='image2' />"
image[3]="<img src='/images/image3.gif' width='139' height='162' alt='image3' />"

var rand_no = Math.floor((3-1)*Math.random()) + 1;

document.write(image[rand_no]);
-->
</script></td>


Is This A Good Question/Topic? 0
  • +

#3 CTphpnwb   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3826
  • View blog
  • Posts: 13,946
  • Joined: 08-August 08

Re: Help with Random Number Generators

Posted 14 June 2009 - 11:56 PM

Try:

var rand_no = Math.floor(Math.random()*3) + 1;

and if images is in your root directory, use: 'images/filename.gif...
Was This Post Helpful? 1
  • +
  • -

#4 DeceitfulPillow   User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 35
  • Joined: 22-June 08

Re: Help with Random Number Generators

Posted 15 June 2009 - 12:39 AM

thank you. I didn't realize the / in front of the images directory was causing a problem.
Was This Post Helpful? 0
  • +
  • -

#5 forest51690   User is offline

  • D.I.C Regular
  • member icon

Reputation: 58
  • View blog
  • Posts: 340
  • Joined: 20-March 09

Re: Help with Random Number Generators

Posted 15 June 2009 - 06:24 AM

Also, aviod named constants, like the 3 in this code, which represents the length of the array:
var rand_no = Math.floor((3-1)*Math.random()) + 1;


you should use image.length in its place. This is good practice so that when you shange the number of image's elements, you don't have to change anything else in the code. It saves debugging.

This post has been edited by forest51690: 15 June 2009 - 06:24 AM

Was This Post Helpful? 1

Page 1 of 1