Как сравнить отмеченную радиокнопку с конкретным значением массива?

0

(JavaScript и начинающий jQuery - будьте осторожны.)

Я пытаюсь сделать свое первое приложение JavaScript/jQuery - простая опрос с тремя вопросами, только одна кнопка, которая выводит окончательный результат в конце. У меня есть все, кроме проверки переключателей - тупик. Невозможно выяснить, как проверить, правильно ли установлен переключатель ("correctAnswer" в начальном массиве ниже). Будь благодарен за любую помощь.

QUIZ.JS

$(document).ready(function(){

var allQuestions = [
{question: "1: Who is Prime Minister of the United Kingdom?", choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"], correctAnswer:0},
{question: "2: What is Barack Obama middle name?", choices: ["Liberal", "Hussein", "Osama", "Joseph"], correctAnswer:1},
{question: "3: Who was President during the Civil War?", choices: ["Harry Truman", "John Tyler", "Abraham Lincoln", "John Adams"], correctAnswer:2}
];

var i = 0; //keep track of which question we're displaying.
var numCorrect = 0; // keep track of the number of correct answers.


    $("button").on('click',function(){  //when the button is clicked,

         // display the next question and all the possible answers...
         if (i < allQuestions.length) //if the question counter is less than the length of the array of answers...
           {
            $('#question').remove();  //remove the current question...
            $('.answerlist').remove();  //and remove the current list of answers...
            $('#questionhead').after('<p id="question">' + allQuestions[i]['question'] + '</p>'); //display the current question
            $('#answerhead').after("<form id='answerform'>");

            // display all the answers for the current question
            for (q=0; q < allQuestions[i]['choices'].length; q++){
               $('#answerform').after("<div class='answerlist'> <input type='radio' name='" +  allQuestions[i]['choices'][q]  +  "'>" + allQuestions[i]['choices'][q] + '<br /></div>');
               }
            $('button').before("</form>");

           i += 1;

           } else {
           $('#questionhead').remove();
           $('#answerhead').remove();
           $('#question').remove();  //remove the current question...
           $('.answerlist').remove();  //and remove the current list of answers...
           $('button').before('<h3>Final score:</h3> You got ' + numCorrect + ' out of 3 questions correct.');
           $('button').remove();
            }
    });

});

И HTML-страница:

<html>

  <head>

    </head>

 <body>
<h1>JavaScript Quiz</h1>
<hr>


<h2 id = "questionhead">Question</h2>

<h2 id="answerhead">Answer</h2>

<p></p>
<button type = "button">Next Question</button>

<!-- Best practice: Load javascript file and jQuery at bottom of page, just before <body> tag. -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="quiz.js"></script>



</body>

</html>

Здесь jsfiddle: http://jsfiddle.net/9pjW6/

  • 0
    Если я могу предложить предложение, я думаю, что было бы лучше сохранить связанный текст каждого радиовхода как его атрибут «value», а не как его атрибут «name». Каждый радиовход в группе ответов должен иметь одинаковый атрибут «имя» - это позволит пользователю выбрать только один ответ из группы.
Теги:
arrays
forms

1 ответ

0
Лучший ответ

Вы можете поместить атрибут идентификатора данных на свои входы и проверить, соответствует ли выбранный входной идентификатор данных правильному номеру ответа. Что-то вроде:

$("button").on('click',function(){

       if($("input:checked").length){
           if($("input:checked").attr("data-id")==allQuestions[i-1].correctAnswer){
               numCorrect+=1;
           }
       }

if (i < allQuestions.length) {

 //etc
for (q=0; q < allQuestions[i]['choices'].length; q++){
               $('#answerform').after("<div  class='answerlist'> <input data-id='"+q+"' type='radio' name='" +  allQuestions[i]['choices'][q]  +  "'>" + allQuestions[i]['choices'][q] + '<br /></div>');
 }
//etc

}

Полный код: http://jsfiddle.net/6TUYM/2/

  • 0
    Отлично - я понимаю, что вы имеете в виду, спасибо. Однако, когда я запускаю ваш код, оценка верна, если один верен, если два верен - но никогда, если три верны. У меня где-то должна быть проблема со счетчиком ...
  • 0
    Моя ошибка, изменила это. должен работать сейчас
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню