I have elements with class “selectElement”. When I click on element with that class, I “select” it, and give it another class “selectedElements”, if it doesn’t already have it.
But, I have a button that should randomly select certain number (e.g. 10) of elements with class “selectElement” and give them the “selectedElement” class.
I tried something like in this answer -> https://stackoverflow.com/a/1764629/1011539, but it returns same values every time…
EDIT: Solved with Jon’s help. Here is the code for other users with similar problem 🙂
$("#chooseElementsRand").live("click",function(){
$(".selectedElements").removeClass("selectedElements");
var maxNum = parseInt($(".maxNum").html());
var randomElements = shuffle($(".selectElement")).slice(0,maxNum).addClass("selectedElements");
$(".selectedNum").html(randomElements.length);
if(randomElements.length==maxNum) {
$(".buttonToProceed").removeClass("notShown");
}
});
Whenever you want to pick N elements really at random out of X, the solution is the Fisher-Yates shuffle. This page has a Javascript implementation (plus rationale, plus nice animations, so go have a look):
Given the shuffle, you can then pick X elements at random with
Here’s a working fiddle to play with.
Footnote: since you are only interested in a certain amount of random picks, there’s no need to unconditionally shuffle the whole input array as
shuffledoes above; you could shuffle only a small part and then use.sliceto cut it off and work with it. I ‘m leaving this as an exercise; be careful that you don’t grab the *un*shuffled part by mistake!