I'm trying to process multiple forms with fieldset inside This is a test for 40 questions, each question with 4 answers. I need to get each answer from radio button that the users picks and use it to count correct answers.
I have some comments along the code to help out, if anything is needed let me know. Thanks for any help.
My index.js code
import express from "express";
import bodyParser from "body-parser";
import pg from "pg";
const db = new pg.Client({
user: "postgres",
host: "localhost",
database: "world",
password: "***", // don't post your password!
port: 5432,
});
const pool = new pg.Pool({
user: "postgres",
host: "localhost",
database: "world",
password: "***",
port: 5432,
});
const app = express();
const port = 3000;
db.connect();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
// Shuffling function based of fisher yates algorithm
const shuffle = array => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
let questions = [];
app.get("/", async (req, res) => {
//Generates random of questions IDs.
for (let i = 0; i < 3; i++) {
let questionId = Math.floor(Math.random() * 70);
questions.push(questionId);
};
// Query questions IDs from DB and shuffles the answers
let arrayToShuff = [];
let shuffledArray = [];
const result = await pool.query(`SELECT * FROM theoryhebrew WHERE questionid = ANY($1::int[])`, [questions]);
for (let i = 0; i < 3; i++) {
arrayToShuff = [result.rows[i].answer1, result.rows[i].answer2, result.rows[i].answer3, result.rows[i].answer4];
shuffle(arrayToShuff);
shuffledArray = [arrayToShuff[0], arrayToShuff[1], arrayToShuff[2], arrayToShuff[3]];
result.rows[i].answer1 = shuffledArray[0];
result.rows[i].answer2 = shuffledArray[1];
result.rows[i].answer3 = shuffledArray[2];
result.rows[i].answer4 = shuffledArray[3];
};
return res.render("index.ejs", {
questionsResults: result.rows,
answersShuffled: shuffledArray
});
});
for (let i = 0; i < 3; i++) {
let questionId = Math.floor(Math.random() * 70);
questions.push(questionId);
};
app.post("/submit", async (req, res) => {
const submittedAnswer = req.body.answer;
res.send(req.body);
console.log(req.body);
const result2 = await db.query(`SELECT answer1 FROM theoryhebrew WHERE questionid = ANY($1::int[])`, [questions]);
const correctAnswer = result2.rows[0].answer1;
if (submittedAnswer == correctAnswer) {
console.log("This is correct");
} else {
console.log("Sorry, this is incorrect");
}
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
My index.ejs file.
<!DOCTYPE html>
<html lang="he" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>שאלות תאוריה</title>
<link rel="stylesheet" href="/styles/main.css">
</head>
<body>
<% questionsResults.forEach(question=> { %>
<form action="/submit" method="post" name="<%= question.questionid %>">
<fieldset form="<%=question.questionid %>">
<legend>
<%= question.questiontext %>
</legend>
<div>
<input type="radio" id="answer1" name="answer" value="<%= question.answer1 %>" checked />
<label for="answer1">
<%= question.answer1 %>
</label>
</div>
<div>
<input type="radio" id="answer2" name="answer" value="<%= question.answer2 %>" />
<label for="answer2">
<%= question.answer2 %>
</label>
</div>
<div>
<input type="radio" id="answer3" name="answer" value="<%= question.answer3 %>" />
<label for="answer3">
<%= question.answer3 %>
</label>
</div>
<div>
<input type="radio" id="answer4" name="answer" value="<%= question.answer4 %>" />
<label for="answer4">
<%= question.answer4 %>
</label>
</div>
<h2>
מספר שאלה לפי מאגר שאלות: <%= question.questionid %>
</h2>
</fieldset>
</form>
<% }) %>
<button type="submit">שלח תשובה</button>
<!-- <form class="container" action="/submit" method="post">
<div class="horizontal-container">
<h3>
Total Score:
<span id="score">
</span>
</h3>
</div>
</form>
<script>
var wasCorrect = "<%= locals.wasCorrect %>";
console.log(wasCorrect)
if (wasCorrect === "false") {
alert('Game over! Final best score: <%= locals.totalScore %>');
document.getElementById("app").innerHTML = '<a href="/" class="restart-button">Restart</a>'
}
</script> -->
</body>
</html>