Le he pedido a ChatGPT que me haga una muestra de un programa para preguntas y respuestas múltiples en javascript.
Aquí tenéis la respuesta:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript Multiple Choice Questions</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
h1 {
text-align: center;
}
.question {
margin-bottom: 20px;
}
.options {
margin-top: 10px;
}
.submit-btn {
display: block;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>JavaScript Multiple Choice Questions</h1>
<div id="quiz-container">
<div class="question">
<h3>1. What is the result of the following expression: 2 + 2 + "2"?</h3>
<div class="options">
<input type="radio" name="q1" value="a"> 22<br>
<input type="radio" name="q1" value="b"> 42<br>
<input type="radio" name="q1" value="c"> 222<br>
<input type="radio" name="q1" value="d"> 4
</div>
</div>
<div class="question">
<h3>2. Which method is used to remove the last element from an array?</h3>
<div class="options">
<input type="radio" name="q2" value="a"> pop()<br>
<input type="radio" name="q2" value="b"> shift()<br>
<input type="radio" name="q2" value="c"> slice()<br>
<input type="radio" name="q2" value="d"> splice()
</div>
</div>
<!-- Add more questions here -->
<button class="submit-btn" onclick="submitQuiz()">Submit</button>
</div>
<script>
function submitQuiz() {
const answers = {
q1: getSelectedOption("q1"),
q2: getSelectedOption("q2"),
// Add more answers here
};
// Check answers
const correctAnswers = {
q1: "b",
q2: "a",
// Add more correct answers here
};
let score = 0;
let result = "";
for (const question in answers) {
if (answers[question] === correctAnswers[question]) {
score++;
result += `Question ${question} is correct.<br>`;
} else {
result += `Question ${question} is incorrect.<br>`;
}
}
result += `<br>Your score: ${score}/${Object.keys(correctAnswers).length}`;
document.getElementById("quiz-container").innerHTML = `<h2>Quiz Result</h2>${result}`;
}
function getSelectedOption(questionName) {
const options = document.getElementsByName(questionName);
for (let i = 0; i < options.length; i++) {
if (options[i].checked) {
return options[i].value;
}
}
return null;
}
</script>
</body>
</html>