HTML Random Number Generator
This article is about how to generate HTML random numbers like:
See the Pen
JS random number generator by Wonderdevelop (@wonderdevelop)
on CodePen.
CODE:
<html>
<head>
<title> Random number</title>
</head>
<body>
<p id="number"> </p>
<button id="b" onclick="random()"> Get number </button>
</body>
<script type="text/javascript">
function random(){
document.getElementById("number").innerHTML = Math.floor(Math.random()* 100)
}
</script>
</html>
In the above code, the random numbers generator code is written using HTML and JS.
- First, create a <p> tag with ID and give a name for display numbers.
- Create a <button> with ID and set the onclick attribute as random() in the above code. When the user clicks the button, the random() JS function is called.
- We can display the random number only with the help of javascript. So, we need to write a JS function to display the random number.
- In JS, we write the function random(), so put the keyword “function” and then the function name.
- As in the above code, inside the curly braces call the getelementbyid function and enter the IDname of the <p> tag.
- Then put unequal to (=) and write the code math.floor(Math.random()*100). The code above contains 100, so random numbers within 100 will be displayed, you can put any number in place of 100.
- Run your code and the random numbers will be displayed when the button is clicked.