Reputation: 17
Basically I have this.. but I want the BUTTON to generate the random number.. which currently only happens when I run the html file, which I don't want that to happen. Thanks!
<body>
<form name="rn">
<input type="text" id="tb" name="tb" /></br>
<input type="button" value="Random Number!" onclick="doFunction(Random);" />
</form>
<script type="text/javascript">
function Random() {
return Math.floor(Math.random() * 1000000000);
}
document.getElementById('tb').value = Random()
</script>
Upvotes: 1
Views: 19578
Reputation: 9449
It is firing this on page load:
document.getElementById('tb').value = Random()
To prevent that from happening, wrap it the onclick function thike this:
function doFunction(){
document.getElementById('tb').value = Random()
}
See fiddle: https://jsfiddle.net/t33rdra6/1/
Upvotes: 0
Reputation: 781068
Put the code that sets .value
in a function, and call that from the onclick
function Random() {
return Math.floor(Math.random() * 1000000000);
}
function randomValue() {
document.getElementById('tb').value = Random();
}
<form name="rn">
<input type="text" id="tb" name="tb" />
</br>
<input type="button" value="Random Number!" onclick="randomValue();" />
</form>
Upvotes: 1
Reputation: 1626
Try changing your HTML to this
<form name="rn">
<input type="text" id="tb" name="tb" />
<input type="button" value="Random Number!" onclick="Random();" />
</form>
and your javascript to this
function Random() {
var rnd = Math.floor(Math.random() * 1000000000);
document.getElementById('tb').value = rnd;
}
Upvotes: 3