-
-
Save Kirill255/8f04ba8082c1a289934b5e825067ec2b to your computer and use it in GitHub Desktop.
quiz generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Test generator</title> | |
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> | |
<script async> | |
const data = '[{"answers":[{"correct":true,"title":"Модульный тест"},{"title":"UI-тест"},{"title":"Системный тест"},{"title":"Нагрузочный тест"}],"question_id":"123","title":"Каким типом тестов покрывается бизнес-логика?"},{"answers":[{"title":"100%"},{"correct":true,"title":"Зависит от требований к надежности"},{"title":"80%"},{"title":"50%"}],"question_id":"124","title":"Какое покрытие кода считается нормальным?"}]'; | |
var questionsData = null; | |
try { | |
questionsData = JSON.parse(data); | |
} catch(error) { | |
console.error( | |
"Не удалось обработать вопросы, проверьте формат данных\n", | |
error | |
); | |
} | |
</script> | |
</head> | |
<body> | |
<div class="container"> | |
<h1>Test</h1> | |
<div id="test"></div> | |
</div> | |
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> | |
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> | |
<script> | |
function generateQuestions(questions, containerId) { | |
const container = document.querySelector(`#${containerId}`); | |
const currentAnswers = {}; | |
if (container !== null) { | |
container.innerHTML = generateForm(questions); | |
} | |
// для описания шаблона формы | |
function generateForm(items) { | |
return ` | |
<form action="#" method="post" id="quiz"> | |
${items.reduce((content, item) => ` | |
${content}${getQuestionMarkup(item)} | |
`, | |
'') | |
} | |
<input type="submit" value="Проверить" class="btn btn-success"> | |
</form> | |
`; | |
} | |
// для проверки ответов | |
(document.querySelector('#quiz')).addEventListener('submit', function (e) { | |
e.preventDefault(); | |
const rightAnswers = getRightAnswers(); | |
const keys = Object.keys(rightAnswers); | |
for(let key of keys) { | |
const right = rightAnswers[key]; | |
const current = currentAnswers[key]; | |
if (right !== current) { | |
markAsInvalid(key); | |
} else { | |
markAsValid(key); | |
} | |
} | |
}); | |
// для фиксации текущих ответов по клику на input | |
(document.querySelector('#quiz')).addEventListener('change', function (e) { | |
const {name:key, value:answer} = e.target; | |
currentAnswers[key] = answer; | |
}) | |
// для получения списка верных ответов | |
function getRightAnswers() { | |
const result = {}; | |
questionsData.forEach(question => { | |
const rightTitle = question.answers.filter( | |
answer => answer.correct | |
)[0].title; | |
result[question.question_id] = rightTitle; | |
}); | |
return result; | |
} | |
// для отметки неверных ответов | |
function markAsInvalid(index) { | |
const el = document.querySelector(`[data-index="${index}"]`); | |
el.classList.remove('alert-success'); | |
el.classList.add('alert-danger'); | |
} | |
// для отметки верных ответов | |
function markAsValid(index) { | |
const el = document.querySelector(`[data-index="${index}"]`); | |
el.classList.remove('alert-danger'); | |
el.classList.add('alert-success'); | |
} | |
// для шаблона вопроса | |
function getQuestionMarkup (question) { | |
return ` | |
<div class="form-row questions-item alert" | |
data-index="${question.question_id}"> | |
<div class="col"> | |
<div class="question-title lead">${question.title}</div> | |
<div class="question-variants"> | |
${getAnswersMarkup(question)} | |
</div> | |
</div> | |
</div> | |
`; | |
} | |
// для шаблона вариантов ответов | |
function getAnswersMarkup(question) { | |
return question.answers.reduce((content, answer) => ` ${content} | |
<div class="form-check"> | |
<label class="form-check-label"> | |
<input class="form-check-input" | |
type="radio" | |
name="${question.question_id}" | |
value="${answer.title}"> | |
${answer.title} | |
</label> | |
</div> | |
`, | |
''); | |
} | |
} | |
if (questionsData) { | |
generateQuestions(questionsData, 'test'); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment