To work with random numbers in JavaScript, there is a Math Object having function random that can be used to generate random numbers.
Math.random() function generates pseudorandom number in the range 0 to 1.
You can use the following code to generate random numbers less than 1:
<div>
<input
id="txtRandom"
type="text" />
<input
id="btnRandom"
type="button"
value="Generate"
onclick="clickGen();" />
</div>
<script
language="javascript"
type="text/javascript">
function clickGen()
{
document.getElementById('txtRandom').value = Math.random();
}
</script>
It will display the random number in the text field each time you will click on the button.
You can use the following method to generate the numbers less than 10, 100 or 1000:
Range 1 – 10
document.getElementById('txtRandom').value = Math.random() * 10;
Range 1 – 100
document.getElementById('txtRandom').value = Math.random() * 100;
Range 1 – 1000
document.getElementById('txtRandom').value = Math.random() * 1000;
Continue to next tutorial: JavaScript Random Password Generator to learn how to user random method to genarate strong passwords.