JavaScript button click event not working properly

I’m having trouble with my JavaScript code. When I press the button, nothing happens at all. The program is supposed to count how many attempts the computer needs to guess the number I enter in the input field.

I’m working in Adobe Dreamweaver and can’t figure out what’s going wrong. Here’s my code:

<html>
<head>
<meta charset="utf-8">
<title>Number Guessing Game</title>
</head>
<body>
    <p>Pick a number from 1-6:</p>
    <input id="userInput" type="text" />
    <button id="startGame">Begin Game</button>
    
    <script>
    document.getElementById('startGame').onclick = function() {
        var targetNumber = document.getElementById('userInput').value;
        var foundMatch = false;
        var attemptCount = 0;
        
        while(foundMatch == false) {
            var computerGuess = Math.random();
            computerGuess = computerGuess * 6;
            computerGuess = Math.floor(computerGuess) + 1;
            
            if(computerGuess == targetNumber) {
                foundMatch = true;
                alert("Computer found your number!");
                alert("It took " + attemptCount + " attempts");
            } else {
                attemptCount += 1;
            }
        }
    }
    </script>
</body>
</html>

Any ideas what might be causing this issue? The button doesn’t seem to trigger anything when clicked.

Yeah, it’s the string comparison issue, but you’ve got another problem too. You’re incrementing attemptCount after the else, so a first-try win shows 0 attempts instead of 1. Move that increment to the top of your while loop right after the opening brace. Also, add validation to make sure users enter 1-6 before starting - otherwise you’ll get stuck in an infinite loop if someone enters 0 or a letter.

Yeah, it’s the string vs number comparison like everyone said, but here’s another thing - that while loop can run forever if someone picks 6. Pure random chance means you might get unlucky and freeze the browser. I’ve seen it happen. Throw in a max attempt limit or use setTimeout for a small delay so the browser doesn’t lock up. Test it hard too - I had a project that looked fine until I hit edge cases that killed performance.

hey! your code looks good, but try wrapping parseInt() around userInput.value - input fields always return strings. so: var targetNumber = parseInt(document.getElementById('userInput').value);. without it, you’re comparing a string to a number and they won’t match.

This topic was automatically closed 6 hours after the last reply. New replies are no longer allowed.