JSFiddle - React, Tailwind, and code Playground
by wybiral
HTML
<h2>What kind of person are you?</h2>
<form id="quiz-form">
<table id="quiz-table">
</table>
</form>
CSS
h2 {
margin-bottom: 40px;
}
#quiz-table td {
vertical-align: top;
padding: 0 20px 20px 0;
}
input[type="submit"] {
width: 100%;
}
JavaScript
// JSON encoded questions and choices
var questions = [{question: 'Which fruit tastes better?', choices: {Cherries: 'red', Blueberries: 'blue', Oranges: ''}}, {question: 'Which soda would you rather drink?', choices: {CocaCola: 'red', Pepsi: 'blue', Sprite: ''}}, {question: 'Which political party do you prefer?', choices: {Republican: 'red', Democrat: 'blue', Communist: 'red'}}, {question: 'Which flower is prettier?', choices: {Cornflowers: 'blue', Roses: 'red', Daisys: ''}}];
// Build quiz table from JSON data
var table = $('#quiz-table');
$.each(questions, function(i, entry) {
var row = $('<tr></tr>')
.appendTo(table)
.append($('<td></td>').text(entry.question));
var answers = $('<td></td>').appendTo(row);
$.each(entry.choices, function(choice) {
var radio = $('<input type="radio" name="radio' + i + '">');
radio.attr('value', choice);
answers.append($('<div></div>').append(radio, choice));
});
})
;
// Check first choice of each question
$('table tr td div:first-child input').attr('checked', 'checked');
// Append submit button
table.append('<tr><td colspan="2"><input type="submit" /></td></tr>');
$('#quiz-form').submit(function(evt) {
var vector = {red: 0, blue: 0}, answer, component;
// Don't let browser submit form to server
evt.preventDefault();
for (var i = 0; i < questions.length; i++) {
// Find checked answer for this question
answer = $('input[name="radio' + i + '"]:checked').val();
// Grab component (or lack of) to increment
component = questions[i].choices[answer];
if (component in vector) {
vector[component] += 1;
}
}
// Normalize by scaling to 1 / numberOfQuestions
vector.red /= questions.length;
vector.blue /= questions.length;
// Report results
alert('Your red/blue score: ' + JSON.stringify(vector));
return false;
});