Helping ordinary people create extraordinary websites!
   

JavaScript random number?

Monday, 28th September 2009
by Omar


How can I create a random number using JavaScript? I am thinking of building a script that will utilize a random number and need it to be done with JavaScript.



Vader
The use of random numbers in JavaScript is something that is very popular for various goals.

Basic JavaScript Random Number
=-=-=-=-=-=-=-=-=-=-==-=-=-=-=
To create your random number you can use the following JavaScript code:

<script language="JavaScript">
var random_no = Math.random();
document.write(random_no);
</script>

This will produce a random number between 0 and 1.


Setting the number of random options
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
To set a range starting at 0 and including 0 you would multiplying it by X where X is the number of possible results. In my example X is 10.
By adding Math.round we remove all decimal options from being included.

<script language="JavaScript">
var random_no = Math.round(Math.random()*10);
document.write(random_no);
</script>

This will produce a number that could be anything from 0 - 9.


Setting the starting point of a random number
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
To set the starting point of a range we simply add that number.
Eg adding 1 in the code below makes the range begin at 1 since 0+1=1.

<script language="JavaScript">
var random_no = (Math.round(Math.random()*10)+1);
document.write(random_no);
</script>

This will produce a number between 1 and 10.

Best of luck,
V.
Monday, 28th September 2009
Votes:
34
26

More JavaScript Help:
» How to send post data to the server without loading a new page?
» Reference a Field on a Form
» How to do calculations using JavaScript
» How can I count the length of string with JavaScript?
» How can I create a select all link for my text area with JavaScript?
» How to make simple program of Contextmenu in javscript.......? plz snd me the source code of the program..
» Write a javascript code that verifies all textboxes has been filled.
» How to create a Facebook like popop that shows an animation then the content?