-1

At this point I am just testing to see if I can compare the radio button selected with the correct answer in the array. See comments below:

var allQuestions = [{
        "question": "Who was Luke's wingman in the battle at Hoth?",
        "choices": ["Dak", "Biggs", "Wedge", "fx-7"],
        "correctAnswer": 0
    }];


function answerFwd() {
    var answerOutput = " ";
    var itemAnswers = allQuestions;
    var answer = 0;
    var playerTally = 0;
    var playerFeedback = "";
    var playerMessage = document.getElementById("playerMessage");


    // Is this the correct way to store the radio button which is selected?
    var radioValue = $("input[type='radio'].radioButtons").is(':checked');

    var right = false;

    if (currentAnswer <= itemAnswers.length) {
        currentAnswer++;
    }

    createRadioButtonFromArray(itemAnswers[currentQuestion].choices);

    //Then compare value in array with radioValue value
    if(radioValue == itemAnswers.correctAnswer){
          right = true;
    }           

    if(right) {
        alert("You answered correctly");
    } else {
        alert("Wrong answer");
    }

}

I suspect my mistake is I am not comparing correctAnswer:3 with the radioValue correctly. What would make sense is the index of the button matched with value. Would a for-loop be the best way? Thanks in advance!

UPDATE

This is the code which creates the buttons:

 function createRadioButtonFromArray(array) {
   var len = array.length; 
   var responses = document.getElementById("responses"); 
   responses.innerHTML = ''; 
    for (var i = 0; i < len; i++) {
     radio = document.createElement("input"); 
     radio.type = "radio";
     radio.name = "choices"; 
     radio.className = "radioButtons"; 
     radio.value = i; 
     radio.id = "choice" + i; 
     var radioText = document.createElement("div"); 
     radioText.id = "c" + i; 
     radioText.className = "choiceText"; 
     radioText.innerHTML = array[i]; 
     responses.appendChild(radio); 
     responses.appendChild(radioText); 
   }
}

And this how it renders:

<div id="responses">
<input type="radio" name="choices" class="radioButtons" value="0" id="choice0">
<div id="c0" class="choiceText">The Avenger</div>
<input type="radio" name="choices" class="radioButtons" value="1" id="choice1">
<div id="c1" class="choiceText">Devastator </div>
<input type="radio" name="choices" class="radioButtons" value="2" id="choice2">
<div id="c2" class="choiceText">Conquest</div>
<input type="radio" name="choices" class="radioButtons" value="3" id="choice3">
<div id="c3" class="choiceText">The Executor</div>

Antonio Pavicevac-Ortiz
  • 7,239
  • 17
  • 68
  • 141

1 Answers1

0

Is this the correct way to store the radio button which is selected?

var radioValue = $("input[type='radio'].radioButtons").is(':checked');

No, that would be:

var radioValue = $("input[type='radio'].radioButtons:checked").val();

More

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875