Public
Edited
Sep 12, 2023
2 stars
Insert cell
Insert cell
Insert cell
viewof answers = quizInput({
questions: [
["The earth is a planet", "yes"],
["The sun is a star", "yes"],
["Pluto is a planet", "no"],
["Pluto is a star", "no"]
],
options: ["yes", "no"]
})
Insert cell
answers
Insert cell
function quizInput({ questions, options = ["true", "false"] }) {
let answers = questions.map(() => null);
let root = htl.html`<div
style="
display: grid;
grid-template-columns: repeat(${options.length}, 100px) 200px 50px;"
>
${options.map(
(opt) => htl.html`<div style="font-weight: bold">${opt}</div>`
)}
<div style="font-weight: bold">Question</div>
<div style="font-weight: bold">Right?</div>
${Array.from(questions.entries(), ([i, [question, correct]]) =>
quizInputRow({
question,
options,
correct,
onChange: (newAnswer) => {
answers[i] = newAnswer;
root.value = answers;
root.dispatchEvent(new CustomEvent("input"));
}
})
)}
</div>`;
root.value = answers;
return root;
}
Insert cell
function quizInputRow({
question,
options,
correct,
onChange = () => {}
}) {
let root = htl.html`<div>`;

function setAnswer(answer, initial = false) {
morph(
root,
htl.html`<div style="display: contents">
<form style="display: contents">
${options.map(
(opt) =>
htl.html`<input
name=${question}
type="radio"
value="${opt}"
checked=${opt === answer}
onChange=${() => setAnswer(opt)}
>
<label>${opt}</label>
</input>`
)}
</form>
<div>${question}</div>
<div>${
answer === null ? "" : answer === correct ? "Right" : "Wrong"
}</div>
</div>`
);

root.value = answer;
if (!initial) {
root.dispatchEvent(new CustomEvent("input"));
onChange(answer);
}
}

setAnswer(null, true);
return root;
}
Insert cell
morph = require("https://bundle.run/nanomorph@5.4.2")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more