Home > Enterprise >  Variables changing when they shouldn't
Variables changing when they shouldn't

Time:07-29

I have this code:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    
    <form>
        <input placeholder="GUEEEEEEEEEEEEEEEEEEEES" name="guess" id="guess"/>
        <input type="submit" onclick="check()" value="EEEE"/>
    </form>
    <h1 id="score"></h1>
</body>
<script>
    
    var answer = Math.floor(Math.random()*100);
    var score = 0;
    
    function check(){
        var guess = document.getElementById("guess").value;
        var guessInt = parseInt(guess);
        
        if (parseInt(guess) == answer) {
            alert("you got it!")
        }
        else if (parseInt(guess) > answer) {
            alert("too high")
        }
        else if (parseInt(guess) < answer) {
            alert("too low")
        }
        
        
    }
    
    document.getElementById("score").innerHTML = score;   // < display score

</script>
and in the javascript, I define the variable answer but every time check() runs the variable gets a new value, when I put in a guess I either get a too high too low or you got it alert and I know the variables get new values every time i put in a new guess because I check what the variable is(using a breakpoint to pause) and then put in the correct answer I run the code again putting in the right answer and then I check it again and its different

CodePudding user response:

It gets a new value, because you are not preventing the form from being submitted, thus you are reloading the page after each button click. Try changing the input which has the click listener for check, to a non-submit button type, ie:

Instead of <input type="submit" onclick="check()" value="EEEE"/>, use <button type='button' onclick='check()'>Submit</button>

CodePudding user response:

Try using event.preventDefault() to stop the form from reloading the page each time it is submitted.

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    
    <form>
        <input placeholder="GUEEEEEEEEEEEEEEEEEEEES" name="guess" id="guess"/>
        <input type="submit" onclick="check(event)" value="EEEE"/>
    </form>
    <h1 id="score"></h1>
</body>
<script>
    
    var answer = Math.floor(Math.random()*100);
    var score = 0;
    
    function check(event){
        event.preventDefault()
        var guess = document.getElementById("guess").value;
        var guessInt = parseInt(guess);
        
        if (parseInt(guess) == answer) {
            alert("you got it!")
        }
        else if (parseInt(guess) > answer) {
            alert("too high")
        }
        else if (parseInt(guess) < answer) {
            alert("too low")
        }
        
        
    }
    
    document.getElementById("score").innerHTML = score;   // < display score

</script>

  • Related