Thursday, April 21, 2011

Generating a random number in JavaScript

I cam across a situation where i required to show random value from an javascript array.  The below code would also be useful- if not required- in certain popular JS applications, such as random image script, or random link color generator.

In this JavaScript article, I will show you how to output a random number that falls within the range 1 to X, where X is any integer greater than 1.

The number generated may be unpredictable, but way getting it is not.
To generate a random number in JavaScript, simply use the following code:
<code>var randomnum =Math.floor(Math.random()*11)</code>

where 11 dictates that the random number will fall between 0-10. To increase the range to, say, 100, simply change 11 to 101 instead.

 One we get random number, we can use the same to fetch respective value from an javascript array.

var myArray = new Array();
myArray[] = 'Value 1';
myArray[] = 'Value 2';
myArray[] = 'Value 3';
myArray[] = 'Value 4';
var randomnum = Math.floor(Math.random()*4);

If you are using jquery than to show the value you can do the following:


$('#myid').html(myArray[randomnum]);

 For Plain Javascript:

 document.getElementById('myid').value = myArray[randomnum];


Hope it helps

No comments:

Post a Comment