cigarette_unicorn
cigarette_unicorn

Reputation: 294

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;

}

Upvotes: 0

Views: 1211

Answers (2)

SaiKiran
SaiKiran

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

Rayon
Rayon

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

Related Questions