javascript - Generating random result from array -


i trying generate random result array using javascript. goal is, when user clicks button, want grab random result array named 'favorites'. works once page refreshed, when click @ second time, returns same result.

$('#button').click(function(){         var favorites = ["http://google.com", "http://yahoo.com", "http://msn.com", "http://apple.com"];         var favorite = favorites[math.floor(math.random() * favorites.length)];         var postmessage = "hi favorite site " + favorite;         alert(postmessage);     }); 

try below code.

$('#button').click(function(){     var favorites = ["http://google.com", "http://yahoo.com", "http://msn.com", "http://apple.com"];     var favorite = $.rand(favorites);;     var postmessage = "hi favorite site " + favorite;     alert(postmessage); });   (function($) {     $.rand = function(arg) {         if ($.isarray(arg)) {             return arg[$.rand(arg.length)];         } else if (typeof arg === "number") {             return math.floor(math.random() * arg);         } else {             return 4;  // chosen fair dice roll         }     }; })(jquery); 

updated fiddle:

http://jsfiddle.net/sj74k/2/

thanks,

siva


Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -