How do I create simple code to select 5 names from input?
I want create simple puzzle to select random 5 names from input.
Lets say I want to give a gift for my blog commentators. So I collect their name and paste into textarea
What I have done for now only form at http://jsfiddle.net/CDSuN/
$winner = 'john, micheal, peter, sally, rooney, owen, tevez, ronaldo,开发者_开发百科 wayne rooney, nani';
How can be done to select the winners with php or jquery. Let me know
first put all input text into an array using explode and then choose random value with array_rand
TRIAL
$winArray=explode(",",$winner);
$finalWinner= array_rand($winArray,5)
echo "<pre>";
print_r($finalWinner); // return keys
echo "</pre>";
//to retrieve the name of winners
for($i=0; $i<5; $i++)
{
echo $winArray[$i]."<br>";
}
http://php.net/manual/en/function.array-rand.php
Hope that helps :)
php:
$namesString = 'john, micheal, peter, sally, rooney, owen, tevez, ronaldo, wayne rooney, nani';
$namesArray = explode(",",$namesString);
$randomIndex = rand(0,sizeof($namesArray));
$winner = $namesArray[$randomIndex];
pure javascript:
// names is a textarea... like <textarea id='names'>'john, micheal, peter, sally, rooney, owen, tevez, ronaldo, wayne rooney, nani'</textarea>
var namesString = document.getElementById('names').value;
var namesArray = namesString.split(',');
var randomIndex = Math.floor(Math.random()*namesArray.length+1)
window.alert("The winner is : "+ namesArray[randomIndex]);
Here's a jQuery / javascript way allowing you to change how many numbers are picked if you wanted:
$('input.button').click(function() {
var names = $('#winner').val().split(', ');
var winnersNums = randomNumbers(5, names.length);
var winningDiv = $('#theWinners');
var winners = '';
$.each(winnersNums, function(key, value) {
winners += names[value]+', ';
});
winningDiv.html(winners);
});
function randomNumbers(req, total) {
var nums = [];
while (nums.length < req) {
var temp = Math.floor(Math.random() * (total));
if (!nums.inArray(temp)) {
nums.push(temp);
}
}
return nums;
}
Array.prototype.inArray = function(value) {
for (var i = 0; i < this.length; i++) {
if (this[i] == value) {
return true;
}
}
return false;
}
Added to your demo here
And with comments here
精彩评论