eainnem eainnem - 6 months ago 15
HTML Question

Creating a random number using JavaScript and returning in HTML without using form

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 ///



<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>


/// JavaScript ///



var randomNumberObject = math.floor(math.random()*10);

function randNumberScript () {

document.getElementById("number").innerHTML = randomNumberObject;

}

Answer

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>

Comments