Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pick random number of items randomly in an array

I want to pick random number of inputs randomly in an array of input elements..
If i use the below method i Can get one random item

jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"],
 {
  random: function(a, i, m, r) {
    if (i == 0) {
        jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
    };
    return i == jQuery.jQueryRandom;
 }
});

$("input:random").prop('id')

But I want random number i=of items to be picked randomly in an array.

like image 234
Exception Avatar asked Dec 16 '22 06:12

Exception


2 Answers

You can use jQuery's .filter() method with a function:

$('div').filter(function(){
    return (Math.round(Math.random()) == 1);
}).css({background: 'red'});

jsFiddle example

like image 128
Teneff Avatar answered Jan 05 '23 15:01

Teneff


You currently are checking if the index is equal to the random number. Maybe it´s better to generate a random number for each input and check if its bigger then 1 or smaller. So randomize a number between 0 and 2. something like:

jQuery.extend(jQuery.expr[":"],
 {
  random: function(a, i, m, r) {
    return Math.random() > 0.5;
 }
});

alert( $("input:random").length );

Also if you get a prop from an element, it will only get it from the first one.

like image 35
Niels Avatar answered Jan 05 '23 14:01

Niels