简体   繁体   中英

Javascript if statement doesn't work as expected

I'm trying to create a small survey with a score. I want to make it so once user reaches score "4", it alerts some message. I wrote if statment for it, but for some reason it never alerts. But if I manually change score variable to 4, everything works as expected.

Where am I going wrong?

Here's the code:

http://jsfiddle.net/uy9kq9mx/

<script>
var score = 0;

function checkQuestionOne (){

    var jautViens = document.getElementById('jaut1Pirm');
    var jautDivi = document.getElementById('Jaut1Otra');
    var jautTris = document.getElementById('Jaut1Tres');
    var jautCetri = document.getElementById('Jaut1Cetu');

    if(jautViens.checked) {
        alert(++score)
    }else if(jautDivi.checked || jautTris.checked || jautCetri.checked) {
        alert("Nepareizi")
    }else{
        alert("Izvēlies opciju!")
    }
}

if (score == 4){
    alert(score);

}else{

}

You need to check the condition if the function

 var score = 0; function checkQuestionOne() { var jautViens = document.getElementById('jaut1Pirm'); var jautDivi = document.getElementById('Jaut1Otra'); var jautTris = document.getElementById('Jaut1Tres'); var jautCetri = document.getElementById('Jaut1Cetu'); if (jautViens.checked) { ++score; //since value of score is changed only in this block you can place the if block here if (score == 4) { alert('score is 4'); } } else if (jautDivi.checked || jautTris.checked || jautCetri.checked) { alert("Nepareizi") } else { alert("Izvēlies opciju!") } //keep the if block here, if there are multiple blocks in which the value of score is changed } 
 <h1>Pirmais jautājums (1. pareizā)</h1> <input type="radio" name="jaut1" id="jaut1Pirm" value="pirma" />Šī ir pirmā atbilde <br/> <input type="radio" name="jaut1" id="Jaut1Otra" value="otra" />Šī ir otrā atbilde <br/> <input type="radio" name="jaut1" id="Jaut1Tres" value="tresa" />Šī ir trešā atbilde <br/> <input type="radio" name="jaut1" id="Jaut1Cetu" value="ceturta" />Šī ir ceturtā atbilde <br/> <br/> <button type="submit" onclick="checkQuestionOne();">Spied</button> 

When you keep it outside of the function, the if condition is evaluated only once, but you need to check it everytime the value of score is changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM