user181796
user181796

Reputation: 195

.checked does not work

I have the following code: http://jsfiddle.net/TXQ9U/37/ (see code below)

What i want to achieve is that I press the submit button and I get a pop up saying either the answer is correct or the answer is not correct and add up a score. Think I have it all set up right but do not get it working. Any suggestions?

Dear regards,

Marc

HTML:

<body>

<p> Question 1: what sport does Roger Federed play? </p>
<table width = "200">

    <tr>
        <td> <input type="radio" name="radio" class="a1" value="a1" /> Cricket </td>
        <td> <input type="radio" name="radio" class="a2" value="a1" /> Tennis </td>
        <td> <input type="radio" name="radio" class="a3" value="a1" /> Tennis </td>
        <td> <input type="radio" name="radio" class="a4" value="a1" /> Tennis </td>
    </tr>

</table>

  <button  class="button1"> Submit </button>
<button class ="button2"> Next page</button>


</body>

jQuery

var score= 0;

function submit(){
       var correctanswer = document.getElementById("a2")
       if(correctanswer.checked === true) {
              score++;
              alert("Answer is correct" + score)               
} 
else {
            alert("Answer is not correct")
}
}    


$(".button1").on("click",function(){
alert(submit());
});

Upvotes: 0

Views: 42

Answers (2)

Scott
Scott

Reputation: 13931

Since you're using jQuery:

<body>
    <script type="text/javascript">
        var score = 0;
        $(document).ready(function() {
            $(".button1").on("click", function () {
                submit();
            });
        });

        function submit() {
            var correctanswer = $("#a2");
            if (correctanswer.is(":checked")) {
                score++;
                alert("Answer is correct" + score);
            }
            else {
                alert("Answer is not correct");
            }
        }
    </script>

    <p> Question 1: what sport does Roger Federed play? </p>
    <table width="200">

        <tr>
            <td> <input type="radio" name="radio" id="a1" value="a1" /> Cricket </td>
            <td> <input type="radio" name="radio" id="a2" value="a1" /> Tennis </td>
            <td> <input type="radio" name="radio" id="a3" value="a1" /> Baseball </td>
            <td> <input type="radio" name="radio" id="a4" value="a1" /> Basketbakk </td>
        </tr>

    </table>

    <button class="button1"> Submit </button>
    <button class="button2"> Next page</button>


</body>

Upvotes: 0

adeneo
adeneo

Reputation: 318242

You don't have an element with the ID a2, that would be a class, so getElementById fails
As you're already using jQuery you can do

function submit() {
    var correctanswer = $(".a2");
    if (correctanswer.is(':checked')) {
        return "Answer is correct";
    } else {
        return "Answer is not correct";
    }
}

FIDDLE

Upvotes: 3

Related Questions