Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need help working with javascript [closed]

Tags:

javascript

I have created this javascript which generates a random number ranging from 0-20. What I want to do is create a text field where the user has 4 attempts to guess the generated number. How would I do this?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<form><input name="code" id="code" type="text" value="" ></input>
<script type="text/javascript">
function makeid() {
    return Math.floor(Math.random() * 20)
}
</script>
<input type="button" style="font-size:9pt" value="Generate Code" onclick="document.getElementById('code').value = makeid()">
</input>
</form>
</body>
</html>
like image 982
The Count Avatar asked Apr 06 '26 22:04

The Count


1 Answers

You could use a global to track state. However, the security of this is weak, as the user could simply reload the page to circumvent the limit. What you really need to do then is track state on the server side (e.g. database) and then use e.g. an Ajax Call on the browser to do the checking :)

<script type="text/javascript">
var count = 0;
function makeid() {
    count++;
    if (count <= 4) {
      return Math.floor(Math.random() * 20);
    }
    alert('Out of attempts');
}
</script>

Edit Apologies, I've only answered half your question.

  <script type="text/javascript">
        var attempts = 0;
        var secretValue = makeid(); // Calculate the secret value once, and don't vary it once page is loaded
        function makeid() {
            return Math.floor(Math.random() * 20);
        }
        function checkId(userValue) {
            if (parseInt(userValue) == secretValue) {
                alert('Correct');
            }
            else {
                attempts++;
                if (attempts <= 4) {
                    alert('Wrong - try again');
                }
                else {
                    alert('Out of attempts');
                }
            }
        }
  </script>

And then change your click handler to

onclick="checkId(document.getElementById('code').value);"
like image 55
StuartLC Avatar answered Apr 08 '26 12:04

StuartLC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!