0

I made a simple HTML with JS inside, and its about add 1 to variable and keep running until user gets 1 by rng(random number generator). Here's the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript">
        function clicked(){
            var num = Math.floor((Math.random() * 100) + 1);
            var click = 0;

            click = click+1;
            if(num == 1){
                document.getElementById("print").innerHTML="Congratz! You did it in "+click+" times!";
                document.getElementById("press").disabled = true;
            }
            else{
                document.getElementById("print").innerHTML="Not the right number! You 've pressed "+click+" times!";
            }
        }
    </script>
</head>
<h1>TEST YOUR LUCK!</h1>
<body>
    <input type="button" value="Press Me!" id="press" onclick="clicked()">
    <div id="print"></div>
</body>
</html>

At this code, click = click+1 don't work and click is stuck at 1. What should I do?

sorak
  • 2,607
  • 2
  • 16
  • 24
  • 1
    Possible duplicate of [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Aluan Haddad Mar 08 '18 at 00:15

1 Answers1

0

The reason your click stuck to 1 is whenever function called you are declaring click = 0, so it is initialized every time you press the button. So just declare var click outside of function clicked() and see the magic.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript">
        var click = 0;
        function clicked(){
            var num = Math.floor((Math.random() * 100) + 1);

            click = click+1;
            if(num == 1){
                document.getElementById("print").innerHTML="Congratz! You did it in "+click+" times!";
                document.getElementById("press").disabled = true;
            }
            else{
                document.getElementById("print").innerHTML="Not the right number! You 've pressed "+click+" times!";
            }
        }
    </script>
</head>
<h1>TEST YOUR LUCK!</h1>
<body>
    <input type="button" value="Press Me!" id="press" onclick="clicked()">
    <div id="print"></div>
</body>
</html>
sorak
  • 2,607
  • 2
  • 16
  • 24
yajiv
  • 2,901
  • 2
  • 15
  • 25
  • 1
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – T Tse Mar 08 '18 at 00:15
  • @ShioT done (I just posted the code and then writing explanation)from next time onwards i'll do both at same time. – yajiv Mar 08 '18 at 00:18
  • Ah, bad timing on my part then. – T Tse Mar 08 '18 at 00:20