Reputation: 294
Is it possible to generate a random number from JavaScript to HTML using button onclick
but return it through a <div>
? I have looked at other similar questions but they all seem to use either <input>
or <form>
. I am not getting any errors in my browser, when I try this code but the output is coming from the <div>
saying 'undefined' as opposed to a number so I'm obviously not defining number
but I'm just a bit confused by JavaScripts syntax.
<html>
<head>
<script type="text/javascript" src="randRandomScript.js">
</script>
</head>
<body>
<button name="randNumberButton" onclick="randNumberScript()" >Click for Number</button>
<div id="number"></div>
</body>
</html>
var randomNumberObject = math.floor(math.random()*10);
function randNumberScript () {
document.getElementById("number").innerHTML = randomNumberObject;
}
Upvotes: 0
Views: 1211
Reputation: 6504
Use this instead your code because your code is using invalid syntax and also no need to write the javascript function in seperate file ,just write the function in a script tag just above the closing body tag().
Math.floor((Math.random() * 10) + 1);
Upvotes: 0
Reputation: 36609
Use randomNumberObject
variable as local-variable
or else it will not be updated every time button clicked.
Note: Correct the typo @ math
.. It is Math
function randNumberScript() { //Why are you accepting a argument ?
var randomNumberObject = Math.floor(Math.random() * 10); //typo at Math
document.getElementById("number").innerHTML = randomNumberObject;
}
<button name="randNumberButton" onclick="randNumberScript()">Click for Number</button>
<div id="number"></div>
Upvotes: 1