I am trying to find a way to show the answers to some randomly generated questions but the only way I can think of doing it gives an answer to a question that is not seen. The code below produces 10 questions correctly but I need to find a way of displaying the answers. Any help would be appreicated.
Thanks
function createWorksheet1() {
var totalQuestions = 10;
var difficulty = 1000;
var ans;
//column1 easy
for (var i = 0; i < totalQuestions; i++) {
var firstNumber = Math.round(Math.random() * difficulty + 100);
var secondNumber = Math.round(Math.random() * difficulty + 100);
// var ans = firstNumber + secondNumber gives answer to unseen question
document.getElementById('column1').innerHTML += firstNumber + " + " + secondNumber + "<br>"+"<br>"+"<br>"
// document.getElementById('column1').innerHTML += ans seems to give an answer to a unseen problem
}
}
>Solution :
- simply insert the result into the HTML alike string
- use a single function not many (like you’re planning to use) – JS is not about repeating code. Keep DRY. Pass arguments to your function instead
- don’t use
<br><br><br>use CSS instead.
const createWorksheet = (selector, totalQuestions = 10, difficulty = 100) => {
const elCol = document.querySelector(selector);
let html = "";
for (var i = 0; i < totalQuestions; i++) {
const firstNumber = Math.round(Math.random() * difficulty + 100);
const secondNumber = Math.round(Math.random() * difficulty + 100);
const ans = firstNumber + secondNumber;
// Concatenate HTML-alike string
html += `<div class="calc">${firstNumber} + ${secondNumber} = ${ans}</div>`;
}
elCol.innerHTML = html; // insert only once:
};
createWorksheet("#column-easy", 10, 100);
createWorksheet("#column-difficult", 10, 1000);
.calc {
padding: 0.5rem 0;
border-top: 1px solid #ddd;
}
<h3>Easy</h3>
<div id="column-easy"></div>
<h3>Difficult</h3>
<div id="column-difficult"></div>
Your task now is to create also an additional argument that accepts multiplication, division etc, pass it as argument and handle that logic within that single function to be later used i.e: like:
createWorksheet("#column-easy", 10, 10, "+");
createWorksheet("#column-medium", 10, 100, "*");
createWorksheet("#column-difficult", 10, 1000, "/");