Search code examples
javascripthtmlfunctioninnerhtml

Cannot generate random number in JavaScript


The code:

<!DOCTYPE html>
<html>
<head>
<title>Test Your Luck Here!</title>
<script type="text/javascript">
function myFunction() {
var x = Math.floor((Math.random() * 6) +1);
document.getElementById("value1").innerHTML = x;
}
</script>
</head>
<body>
<h1>Test Your Luck Here!</h1>
<p id="value1"></p>
<button onlick="myFunction()">Roll!</button>
</body>
</html>

I am trying to generate any number between 1 and 6 using JavaScript but i haven't been very successful so far. I have tried giving it a variable and an id for my button but it doesn't seem to be functioning. I went on w3schools and they had something similar to this. Thanks.


Solution

  • As @nevermind mentioned that it should be onclick rather than onlick in one line of your code. These kind of syntax errors can happen frequently. Consider using the Browser Debugging Tools or JSBin whenever something doesn't seems to work. You can't post questions here just for SO to figure out your syntax errors. :-)

    Working demo, after changing onlick to onclick.