-2

Markup:

<ul>
<li>Bla</li>
<li>Ble</li>

...


<li>zla</li>
</ul>

Lets asume its a really long list, how can i select x items, but randomlly?

-edit-

Not exact duplicate, i am trying to select x items;

something like:
var i = 0;
$("li:random").each(function(){
    i++; if(i==50) break;
})
Toni Michel Caubet
  • 19,333
  • 56
  • 202
  • 378

5 Answers5

3

Here is a quick example of how to get this using javascript random function:

$(function() {
    var randomItemsNum = 3;
    var totalItems = $('#mylist > li').length;

    for (var index = 0; index < randomItemsNum; index++) {
        var randomIndex = Math.floor((Math.random() * totalItems) + 1);
        var item = $('#mylist > li:nth-child(' + randomIndex + ')');
        if (item.hasClass('selected')) {
            index--;
            continue;
        }
        else {
            item.addClass('selected');
        }
    }
});

It adds CSS class selected to 3 random list items. Check working demo here - http://jsfiddle.net/Pharaon/PPW9J/1/

Sergey Rybalkin
  • 3,004
  • 22
  • 26
1
function selectRandomFromList($list, num){
    var $children = $list.children(),
        len = $children.length,
        a = [],
        o = {},
        r,
        $items = $([]);

    if (!len) { return $items; }
    if (num >= len) { return $children; }

    // Build an array of unique indices
    while (a.length < num) {
        r = Math.floor(Math.random() * len);
        if (!o.hasOwnProperty(r)) {
            o[r] = 1;
            a.push(r);
        }
    }

    // grab the items
    while (num--) {
        $items = $items.add($children.eq(a.pop()));
    }

    return $items;
}

Example usage:

selectRandomFromList($('ul'), 3);

Demo:

http://jsfiddle.net/lbstr/d8JgP/

lbstr
  • 2,822
  • 18
  • 29
0
  1. Choose a random number (r) between 1 and the length of the list.
  2. Pick all elements where el# % r == 0.

Done. :)

Esteban Araya
  • 29,284
  • 24
  • 107
  • 141
0

I think you could get away with doing something like this:


var list_length = $("ul li").length;
var x; //Assign amount of items
for(var i = 0; i <= x; i++) {
   Math.floor((Math.random()*list_length));
   //Select stuff in here
}
ayyp
  • 6,590
  • 4
  • 33
  • 47
0

Do this way:-

randomList = 8;

randomElements = jQuery("li").get().sort(function(){ 
  return Math.round(Math.random())-0.5
}).slice(0,randomList);

$(randomElements).addClass("activeLI");​

CSS

.activeLI {
    color: red;
}​

Change randomList number 8 to 50 or any number.

Refer to the LIVE DEMO

copied from jQuery: select random elements this answer.

Community
  • 1
  • 1
Siva Charan
  • 17,940
  • 9
  • 60
  • 95