Reputation: 1491
I'm trying to create a random select from an already existing select, but it's not working as expected.
It's removing elements from the original for some reason I'm confused as to why
http://jsfiddle.net/t1dukhwz/51/
var sizeofmenu = $('.random_menu').children().length;
var myArr = new shuffle(ArrMap(0,sizeofmenu));
var newmenu = $('.new_menu');
$(myArr).each(function(i,v) {
//console.log(v);
newmenu.append($('.random_menu').children().eq(v));
});
function ArrMap(start, count) {
if(arguments.length == 1) {
count = start;
start = 0;
}
var foo = [];
for (var i = 0; i < count; i++) {
foo.push(start + i);
}
return foo;
}
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
Upvotes: 0
Views: 59
Reputation: 449
So what's happening is: when you reference $('.random_menu').children().eq(v)
it is referring to the actual element in the DOM. So if you append that element somewhere else (in this case the '.random_menu') it removes it from its current location and appends it to the new location. The side effect of this is that the size of your array shrinks by one, and the indexes you've randomized get blown to hell.
To avoid this, you could simply clone the original array, like so:
var original = $('.random_menu').children().clone();
var sizeofmenu = original.length;
var myArr = new shuffle(ArrMap(0,sizeofmenu));
var newmenu = $('.new_menu');
$(myArr).each(function(i,v) {
newmenu.append(original.eq(v));
});
Fiddle: http://jsfiddle.net/t1dukhwz/58/
Upvotes: 1
Reputation: 1
The follwing code sample is working as expceted keep a a cache
Update code link http://jsfiddle.net/bibumathew/t1dukhwz/55 {code}
var cacheMenu = $('.random_menu').html();
var cacheMenu = $('.random_menu').html();
{/code}
Upvotes: 0
Reputation: 11416
I've just adjusted your Fiddle changing
newmenu.append($('.random_menu').children().eq(v));
to
newmenu.append($('.random_menu').children().eq(v).clone());
Upvotes: 0