Reputation: 49
How could I generate a random number every refresh using html and javascript?
I have the javascript that would generate a decimal number.
function DecimalGenerate() {
var min = 1.03,
max = 5.99,
NumberResult = Math.random() * (max - min) + min;
alert(parseFloat(NumberResult).toFixed( 2 ));
};
DecimalGenerate();
Upvotes: 0
Views: 3694
Reputation: 1
Below answer worked for me but how to remove . from result (1752115.32)
JQuery
function DecimalGenerate() {
var min = 1.03,
max = 5.99,
NumberResult = Math.random() * (max - min) + min;
$('#text1').val(parseFloat(NumberResult).toFixed( 2 ));
};
$( document ).ready(function() {
DecimalGenerate();
});
Upvotes: 0
Reputation: 7
<html>
<head>
</head>
<body>
<p id="new">this is a number</p>
<script>
(function () {
document.getElementById("new").innerHTML = Math.floor(Math.random()*100);
})();
</script>
</body></html>
it is a self invoking function and for each time we refresh the window it cahanges it's value randomly between 0 to 1 and multiplying it by 100 and then use floor function give us value between 0 to 100.
Upvotes: 0
Reputation: 11808
you can simply call that fucntion on JQuery.( document ).ready(). I have displayed the random generated number in text box
Html
<input type='text' id='text1'>
JQuery
function DecimalGenerate() {
var min = 1.03,
max = 5.99,
NumberResult = Math.random() * (max - min) + min;
$('#text1').val(parseFloat(NumberResult).toFixed( 2 ));
};
$( document ).ready(function() {
DecimalGenerate();
});
You can check this Demo
Upvotes: 1
Reputation: 21
You can also have a button that generates a random number every time you press the button. The button triggers the function to be executed, thus generating the random number and appending it to the h3 tag of the html document.
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Generate Random Number</h1>
<h3 id="rand"></h3>
<button onclick="DecimalGenerate();">Random</button>
</body>
<script src="script.js"></script>
</html>
script.js
function DecimalGenerate() {
var min = 1.03,
max = 5.99,
NumberResult = Math.random() * (max - min) + min;
var rand = document.getElementById('rand');
rand.textContent = NumberResult.toFixed( 2 );
};
DecimalGenerate();
Here is a link to Plunker.
Upvotes: 0