INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

Functions

Randomizing a list of items by caitlin
Posted: 11 Jul 03

Recently I had to create an online quiz, and we needed the answers to each question to appear in random order. I found that it's very easy to do in Javascript. Here's an example of a randomized list of choices:

1. First, create an array and name it ("choices")
2. Then list the items in the array (with html coding inside the single quotes)
3. Create a function that sorts the array based on a randomly generated number.
4. Finally, write the choices to the page (document.write).

Hope you find it useful!

<script language=javascript type="text/javascript">
choices=new Array()
choices[0]='<li>Mauve</li>'
choices[1]='<li>Peridot</li>'
choices[2]='<li>Ecru</li>'
choices[3]='<li>Puce</li>'
function RandomSort() {
return Math.floor((Math.random()*4)-1)
}
choices=choices.sort(RandomSort)
document.write(choices)
</script>

Back to Javascript FAQ Index
Back to Javascript Forum

My Archive

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close