JSFiddle - React, Tailwind, and code Playground
CSS
div {
max-width:500px;
margin:0 auto;
padding:15px;
background:whitesmoke;
}
div * {
display:block;
margin:0 auto;
padding:2px;
text-align:center;
position:relative;
}
input {
display: inline;
margin-left: 20px;
position: absolute;
right: calc(50% - 75px);
}
label{
left:-20px;
}
h1{
font-family:sans-serif;
}
JavaScript
var allQuestions = [{
question: "Who is Prime Minister of the United Kingdom?",
choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
correctAnswer: 0
}];
container = document.createElement("div");
var title = document.createElement("h1");
var question = document.createTextNode(allQuestions[0].question);
title.appendChild(question);
container.appendChild(title);
for (var i in allQuestions[0].choices) {
var option = document.createElement("input");
option.setAttribute("type", "radio");
option.setAttribute("name", "PM");
label = document.createElement("label");
labelText = document.createTextNode(allQuestions[0].choices[i]);
label.appendChild(labelText);
label.appendChild(option);
container.appendChild(label);
}
var submit = document.createElement("button");
submit.appendChild(document.createTextNode("Check Your Answer"));
container.appendChild(submit);
document.body.appendChild(container);
cIndex = allQuestions[0].correctAnswer + 1;
function check() { //correctAnswer + 1 because the container also contains the h1
cIndex = allQuestions[0].correctAnswer + 1;
var shouldCheck = false;
var radios = document.getElementsByName("PM");
for (var o in radios) {
if (radios[o].checked) {
shouldCheck = true;
}
}
if (shouldCheck) {
container.children[cIndex].style.color = "green";
container.children[cIndex].style.fontWeight = "bold";
if (container.children[cIndex].children[0].checked) {
container.appendChild(document.createElement("p").appendChild(document.createTextNode("You got it right!")));
} else {
container.appendChild(document.createElement("p").appendChild(document.createTextNode("You got it wrong :(")));
}
}
}
submit.addEventListener("click", check);