Pick random depending on value using jquery?!?!

I have this script where I can move users from one multiple selectbox to another and it works fine, but…

I want to add a button, beside the “Add” and “Remove” button which pick random of users depending on a given value, lets say that the value is 2, then it would pick 2 users randomly and move them to box 2, I just don’t know how… Please help…

Current javascript

$().ready(function() {
   $('#add').click(function() {
    return !$('#box1 option:selected').remove().appendTo('#box2');
   });
   $('#remove').click(function() {
    return !$('#box2 option:selected').remove().appendTo('#box1');
   });
  });

The HTML:

<table>
	<tr>
		<td valign="top"><select multiple id="box2" style="width:250px;height:200px;"></select></td>
		<td width="100%" align="center"><a href="#" id="add">Add</a><br><a href="#" id="remove">Remove</a></td>
        <td valign="top">
        	<select multiple id="box2" style="width:250px;height:200px;">
        					<option value="1">User 1</option>
                            <option value="2">User 2</option>
                            <option value="3">User 3</option>
                            <option value="4">User 4</option>
           </select>
        </td>
	</tr>
</table>

Please help… Thanks :slight_smile:

Where does this “given value” come from? Also, your first SELECT is empty, and both your SELECTs have the same ID. This is illegal, as the ID must be unique.

Still, to select random values:

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

assuming select1 contains at least 2 options and select2 is empty.

There might be a better way of doing this with jQuery, but I’m not familiar with it enough to know.

Sorry about the ID’s… Miswritten… I will try it out… What id should I give the “Random” button?

It doesn’t matter. You just have to wrap all the javascript I gave you above in a function, and run it when the button is clicked.

By the way, you should NOT be using a table for this layout. A table is for tabular data. That is not tabular data.

Allrighty then… I got it, but what if I want to specify the number instead of using a random number…?

Specify which number? The number of random options to use? It’s already specific, you have to provide it.

Sorry for my lack of expertize…Where?!?

If its the:
var given = 2

then it doesnt do the job… When clicking on the button it submits all the users in select1 to select2!!!

No it doesn’t. If #select2 is empty, then only 2 (random) items from #select1 will get moved there. Is that not what you wanted? If not, you have to be clearer, with examples.

That is exactly what I wanted, but as it is now… It moves all from #select1 to #select2.

The users I have in #select1 is from a db table… Does that change anything?

Here is all my script…

$().ready(function() {
   $('#add').click(function() {
    return !$('#select1 option:selected').remove().appendTo('#select2');
   });
   $('#remove').click(function() {
    return !$('#select2 option:selected').remove().appendTo('#select1');
   });
  });
  
function randomusers(){
  var given = 2, used = {}, randnum, opts = $('#select1 option'), olen = opts.length;
	function ran() { // generate a unique random number
	  randnum = Math.floor(Math.random() * olen);
	  //randnum = 2;
	  if (!used['u'+randnum]) return randnum;
	  else ran();
	}
	for (var i = 0; i < given; i++) { // get the correct quantity of randoms
	  used['u'+ran()] = true;
	}
	opts.filter(function(index) { // remove all options that are not one of the randoms
	  return !!used['u'+index];
	});
	$('#select2').append(opts); // append random options to other SELECT
}
echo '<table width="100%">
		<tr>
			<td><h4>New Group</h4></td><td></td><td><h4>All Members</h4></td>
		</tr>
		<tr>
			<td valign="top"><select multiple id="select2" class="input_field" style="width:250px;height:200px;"></select></td>
			<td width="100%" align="center"><a href="#" id="add" class="btn_red_25x25_arrow_left" title="Add"></a><br>
			<input value="" type="button" onClick="randomusers();" onmouseover=style.cursor="pointer" class="green_random_25btn" /><br>
			<a href="#" id="remove" class="btn_black_25x25_arrow_right" title="Remove"></a></td>
			<td valign="top"><select multiple id="select1" class="input_field" style="width:250px;height:200px;">';
			
			$sql="SELECT * FROM ".$prefix."_club_users 
					INNER JOIN ".$prefix."_users ON ".$prefix."_club_users.new_userid = ".$prefix."_users.new_userid
					WHERE clubid='$clubid' ORDER BY ".$prefix."_users.fname ASC";
			$result = mysql_query($sql);
			while($row = mysql_fetch_array($result)){
				
				echo '<option value="'.$row['new_userid'].'">'.$row['fname'].' '.$row['lname'].'</option>';
				
			}
			
			echo '</select></td>
			</tr>
		</table>';

Hope this helps!

It doesn’t work because the javascript you’re using is not the same as what I posted. I edited it about 30 seconds after I posted it, so you must have copied it then! Use the JS I posted above, you’ll see it works (I tested it).

Oh yeah… Thanks… It works allmost perfect. Sometimes it only takes 1 instead of 2 if I only have lets say 5 options in #select1??? How can that be?

Hmm that’s odd, I’ll see what I can come up with.

Simple mistake… this should work now!

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<select id="select1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<select id="select2">
</select>
<script>
var given = 2, used = {}, randnum, opts = $('#select1 option'), olen = opts.length;
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;
}
opts.filter(function(index) { // remove all options that are not one of the randoms
  return !!used['u'+index];
}).appendTo('#select2');
</script>
</body>
</html>

Thanks… Your the man :slight_smile:

Sorry to come back again! :expressionless:

I have one more question… I have pulled my head to figure out how to add a “createElement” to your script… I need to add hidden input fields to the scriipt to be able to pass it on to a db table… I have been surfing around the net and found that I need to use createElement but dont know where to put it in your script…

I think it should be near the “appendTo(‘#select2’);” but not sure…

Please help :slight_smile:

First of all, if I have understood what you want, if you give name for both of the selects then they will be submitted themselves when you submitted the form. So I didn’t quite get that which new value you want to submit by creating new hidden field.

And regarding creating new element and storing the value in it, I think you should know yourself which value and after what you want to post. Since there are/maybe more than one options in both of the selects so I am confused which value you want to store in a new element for posting. And regarding creating element/hidden field, you can rather just have one predefined hidden field and store the value in it since hidden field is always invisible in the page/form.

As you can see the script picks random from #select1 and insert them to #select2. It is these random picks I want to store in new elements…

Do you mean all the random picks or one of them? If all, then each in different hidden field or in a single field with comma separated or something else?

Its All of the random picks, and one single comma seperated is what i was thinking…