Тест с чекбоксами
Дано: есть тест с вариантами ответов по чекбоксам. (через localStorage и шаблонизатор все прогоняется в учебных целях).
Правильный вариант ответа только один. Не могу сообразить, как правильно сверить выбранный вариант с верным. Подскажите, плз. 'use strict'; $(function() { var preQuestions = [ { question: 'Question 1', answers: ['Answer 1', 'Answer 2', 'Answer 3'], correctAnswer: 1 }, { question: 'Question 2', answers: ['Answer 1', 'Answer 2', 'Answer 3'], correctAnswer: 2 }, { question: 'Question 3', answers: ['Answer 1', 'Answer 2', 'Answer 3'], correctAnswer: 3 } ]; localStorage.setItem('preQuestions', JSON.stringify(preQuestions)); var strQuestions = localStorage.getItem('preQuestions'); var questions = JSON.parse(strQuestions); var test = $('#test').html(); var testContent = tmpl(test, { data: questions }); $('.questions__block').append(testContent); var $modal; var $overlay; function showModal(){ $modal = $('<div class="modal"><p class="results"></p></div>'); $overlay = $('<div class="overlay"></div>'); $overlay.on('click', hideModal); $('body').append($overlay) $('body').append($modal) }; function hideModal(){ $modal.remove(); $overlay.remove(); }; $('.test__button').on('click', showModal); $('.test__button').on('click', function(){ var $result; $('input').each(function(i) { console.log(questions[i]); if ( $(this).prop('checked') ) { if ( questions.answers[i] == questions.correctAnswer ) { // ЗДЕСЬ явно неправильно. Как фиксить? $result = true; } else { $result = false }; } }); if ($result) { $('.results').html('Everything is correct'); $('input').removeAttr('checked'); } else { $('.results').html('Wrong answer'); $('input').removeAttr('checked'); } }); }); Изначально я реализовывал по-другому: у input ставил атрибут value="correct" и сравнивал по нему: 'use strict'; $(function() { var preQuestions = [ { question: 'Question 1', answer1: 'Answer 1', answer2: 'Answer 2', answer3: 'Answer 3' }, { question: 'Question 2', answer1: 'Answer 1', answer2: 'Answer 2', answer3: 'Answer 3' }, { question: 'Question 3', answer1: 'Answer 1', answer2: 'Answer 2', answer3: 'Answer 3' } ]; localStorage.setItem('preQuestions', JSON.stringify(preQuestions)); var strQuestions = localStorage.getItem('preQuestions'); var questions = JSON.parse(strQuestions); var test = $('#test').html(); var testContent = tmpl(test, { data: questions }); $('.questions__block').append(testContent); var $modal; var $overlay; function showModal(){ $modal = $('<div class="modal"><p class="results"></p></div>'); $overlay = $('<div class="overlay"></div>'); $overlay.on('click', hideModal); $('body').append($overlay) $('body').append($modal) }; function hideModal(){ $modal.remove(); $overlay.remove(); }; $('.test__button').on('click', showModal); $('.test__button').on('click', function(){ var $result; $('input').each(function() { if ($(this).prop('checked')) { if ($(this).attr('value') == 'correct') { $result = true; } else { $result = false } } }); if ($result) { $('.results').html('Everything is correct'); $('input').removeAttr('checked'); } else { $('.results').html('Wrong answer'); $('input').removeAttr('checked'); } }); }); Но тогда корректно отрабатывается даже при одном правильном ответе. <!DOCTYPE html> <html> <head> <title>TEST</title> <meta charset="utf-8"> <!-- <link rel="stylesheet" href="css/style.css"> --> <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script> <script src="js/template.js"></script> <script src="js/script.js"></script> </head> <body> <div class="test__container"> <h1 class="test__header">Programming test</h1> <div class="questions__block"> <script type="text/html" id="test"> <% for (var i = 0; i < data.length; i++) { %> <h2> <%= data[i].question %> </h2> <input type="checkbox"> <%= data[i].answers[0] %> <input type="checkbox"> <%= data[i].answers[1] %> <input type="checkbox"> <%= data[i].answers[2] %> <% }; %> </script> </div> <a href="#" class="test__button">Review my results</a> </div> </body> </html> |
|
Patrick101,
$(".test__button").on("click", function() { var $result = true; var indx = preQuestions.map(function(el, i) { return el.correctAnswer - 1 + i * 3 }); $("input").each(function(i) { if (~indx.indexOf(i) && !this.checked || !~indx.indexOf(i) && this.checked) $result = false }); if ($result) $(".results").html("Everything is correct"); else { $(".results").html("Wrong answer"); $("input").prop("checked", false) } }); |
рони, спасибо!
А поясни плз конструкцию ~indx.indexOf(i) - с тильдой раньше не сталкивался. |
Patrick101,
замена indexOf(i) != -1 сдвиг в право -- было -1, 0, 1, 2... с ~ стало 0, 1, 2, 3... ~indexOf при нахождении будет всегда положительное число -- иначе ноль или в сравнении нашли значит true, не нашли значит ноль alert(~-1); |
Часовой пояс GMT +3, время: 11:47. |