Thursday, January 20, 2011

Java script Random Draw

If you need to draw randomly from a group of options, and remove the winner from the options; this is the right choice for you.!

Although this example is not that hard if it was applied on any "code behind" language; I decided to increase my javascript skills doing this example; and I wanted to share it with you.

The simple example conaint an input control to display the result and a button to perform the draw; in addition to 16 inputs to enter the results; the user will right up to 16 options or less; and on pressing the button the selected option will be removed.


function PickRandomly( ){

var Array= [ ]; // We will need an array to hold the options in.
var controlID;

var i =1;

while (i<=16) // Check on all the inputs if it is not empty; add the ID to the array.
{
controlID = "var" + i; // Control ID
if (document.getElementById(controlID).value != "")
{
Array.push(controlID);
}
i = i+1;
}

// We have an array filled with the IDs of the available

if (Array.length > 0)
{
var randomnumber=Math.floor(Math.random()*Array.length); // Generate a random number from zero to the maximum length of the array
document.getElementById("result").value = document.getElementById(Array[randomnumber]).value ; // Show the result.
document.getElementById(Array[randomnumber]).value = ""; // and remove it from the available options
}



Please find a running sample here.

No comments: