Random selects into multiple boxes?!?!

I have a script which allows me to select random users from one select field to another and works like a charm, but…

I wan tto be able to get random users from one select field to multiple (lets say 2) other select fields…

So lets say that I have 5 users in the first field (select1):
James
Bill
Jennifer
Bob
Karen

Now when I press a button:
<input value=“” type=“button” onClick=“randomusers();” />

2 users a moved to select2 and other 2 users is moved to select3.

My current script is as follows:

function randomusers(){

	var given = 2, used = {}, randnum, opts = $('#select1 option'), olen = opts.length, hiddiv = $('#hiddendiv');
	function ran() { // generate a unique random number
	  randnum = Math.floor(Math.random() * olen);
	  return used['u'+randnum] ? ran() : randnum;
	}
	for (var i = 0; i < given; i++) { // get the correct quantity of randoms
	  used['u'+ran()] = true;
	}
	var players = opts.filter(function(index) { // remove all options that are not one of the randoms
	  return !!used['u'+index];
	}).appendTo('#select2');
	
}

Hoping for help…

Thanks in advance :slight_smile:

Any ideas anybody?!?!

I have an idea but I cannot put it into code.

If it were mine, I’d take the original list and randomise it. If this required making a new array to store the “post-randomised” list, then so be it.

Then I’d grab 2 items (people) from that list. Since the list is random, you could get away with popping the last two off or unshifting the first two off. You could also have this new array go back in through the randomiser after 2 items are popped/unshifted, for extra uncertainty : )

When pop or unshift returns those two people, have the first set get appendedTo the #select2, and the next couple appendedTo #select 3 and so on until the list is empty.

But, I’m not good enough in JS to realise this as code, I don’t think.

Here’s some functions to help you do it


function extractOption(selectElem, optionIndex) {
    var optionElem = selectElem.options[optionIndex];
    selectElem.remove(optionIndex);
    return optionElem;
}

function rand(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function randomOptionIndex(selectElem) {
    return rand(0, selectElem.length - 1);
}

function extractRandomOption(selectElem) {
    return extractOption(selectElem, randomOptionIndex(selectElem));
}

Here’s a reference to help you understand what’s going on

Then you can just do this to move an option from selectElemA to selectElemB. Both a and b should be <select> element dom objects. Make sure to test selectElemA.length > 0 before trying to move something.


selectElemB.add(extractRandomOption(selectElemA));

Gosh… Thanks, alot of hours, but OK… I will try to figure this out, not a JS wizz though… But thanks for your input…