I want to make a website page for language test that when the user clicks the play button, the numbers of questions and the choices are shown. So I wrote this code:
const audioA = document.getElementById("AudioA");
const playBtn = document.getElementById("PlayBtn");
function playPartA() {
audioA.play();
playBtn.style.color = "#777777";
showQuestion();
}
function showQuestion(){
for(let i = 0; i < 30; i++){
$(".questionBox").append('<div class="Question"></div><div class="Options"><span></span><span></span><span></span><span></span></div>');
}
$(".secondBox").append('<a href="Listening Part A.html" class="btnToPartB">Continue to Part B</a>');
$('.Question').each(function(index){
$(this).html("Number ");
$(this).append(index+1);
});
$('.Options').QuesPartA.forEach(option => {
$('.Options span').eq(0).text(option[0]);
$('.Options span').eq(1).text(option[1]);
$('.Options span').eq(2).text(option[2]);
$('.Options span').eq(3).text(option[3]);
});
};
And this is the array:
let QuesPartA = [
{ option: [
"She doesn't have an appointment",
"She must live somewhere else",
"Her apartment isn't far away",
"Her problem is complicated",
],
answer: 2
},
{ option: [
"There's no charge for phone calls",
"She can call him later if she likes",
"His phone is out of order too",
"She can use his phone if she wants",
],
answer: 1
},
{ option: [
"It was simpler than he'd thought",
"It was too hard to solve",
"He couldn't find it",
"He solved it even though it was hard",
],
answer: 3
}
];
So I use .append to create many boxes for the answer options, then I want to put the value of the option element on that boxes. But I failed. Anyone knows how to do that?
Instead of creating questions first and then populating each with options, you can create both at the same time by iterating thru the questions array like this.
function showQuestion(){
for(let i = 0; i < QuesPartA.length; i++){
$(".questionBox").append('<div class="Question">Number '+ parseInt(i+1) +'</div>');
$(".questionBox").append('<div class="Options" id="optId'+ parseInt(i+1) +'">');
QuesPartA[i]['option'].forEach(option => {
$("#optId"+ parseInt(i+1)).append('<span>'+option +' </span><br>');
});
$(".questionBox").append('</div><br>'); // end Options div
}
$(".secondBox").append('<a href="Listening Part A.html" class="btnToPartB">Continue to Part B</a>');
};
After you initialize the quetionBox with all 30 questions, apply below:
$.each(QuesPartA,function(index,value){
$(".questionBox").find(".Question:eq(" + index + ")").find("span:eq(0)").html(value.option[0]);
$(".questionBox").find(".Question:eq(" + index + ")").find("span:eq(1)").html(value.option[1]);
$(".questionBox").find(".Question:eq(" + index + ")").find("span:eq(2)").html(value.option[2]);
$(".questionBox").find(".Question:eq(" + index + ")").find("span:eq(3)").html(value.option[3]);
});
Logic is simple, based on the QuesPartA array index, find the right question and right span to change its html value.