Quote:
Originally Posted by felgall
The following code worked for me when I tested it. Refreshing the page enough times eventually gets all the values to display and although there was a bias toward 1 & 2 for a while it evened out as I refreshed more times.
|
I do not detect any bias. It worked perfectly on my tests.
Code:
<form>
<select id="s1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
</form>
<script type="text/javascript">
var select= document.getElementById('s1');
for (var i=0; i<100; i++) {
select.selectedIndex= Math.floor(Math.random() * select.options.length);
document.write(select.selectedIndex); // 5315010225244432352211311100014220342110000244505414220343411410140314440031503010011014450553550305
}
</script>
Be aware that
random implies that the same number may be generated 2,3 or possibly even more times in succession, especially with a small number (6) of values.
Another approach would be to shuffle the numbers 1-6 into a random order, and then pick the next one in sequence, thus avoiding consecutive
appearances of the same number.
Code:
<script type = "text/javascript">
Array.prototype.shuffle = function() {
var s = [];
while (this.length) s.push(this.splice(Math.random() * this.length, 1));
while (s.length) this.push(s.pop());
return this;
}
var count = 0;
var arr = [1, 2, 3, 4, 5, 6];
var sarr = arr.shuffle);
document.write(sarr); // for testing
function shownext() {
alert (sarr[count]); // for testing
count ++;
if (count >5) {count = 0}; // start the sequence again
select.selectedIndex = count;
}
</script>