简体   繁体   中英

JavaScript if statement for radio button check

I'm making a simple quiz, using a mixture of AJAX and JavaScript.

The idea is that if you click the right radio button, you'll get a 1 added to your score. But just for now, I want to check it's working by showing an alert that says CORRECT when you check the correct button.

See here, I've only put the code into QUESTION1.

http://fh80.student.eda.kent.ac.uk/fyp-assets/quiz/quiz.php

This is how the radio buttons are coded, with an ID only for the correct answer:

<input type="radio" name="question1" value="thunderbolt">Thunder Bolt<br>
<input type="radio" name="question1" value="lightningbolt" id="lightningbolt">Lightning Bolt<br>

And here is the script that runs. It should dictate that the input with id="lightning" = correctAnswer - and then is correctAnswer is checked, the alert will show. Else it does nothing

var correctAnswer = document.getElementById("lightningbolt");

if (correctAnswer.checked){
    alert("CORRECT");
}
else(){}

This doesn't seem to work and I see no JS errors, what am I doing wrong?

Placing the open and close parenthesis after the else statement causes a syntax error.

if (correctAnswer.checked){
    alert("CORRECT");
}else{

}

JS Fiddle: http://jsfiddle.net/qxb5Z/

Adding the following in the head section should make things work:

<script>
window.onload = function(){
    document.getElementById("question_1a").onclick = function(){
        var correctAnswer = document.getElementById("lightningbolt");
        if (correctAnswer.checked){
            alert("CORRECT");
        }
     };
}
</script>

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