Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Randomizing a list of items

Functions

Randomizing a list of items

by  caitlin  Posted    (Edited  )
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>
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top